Sub topic 4
LightGBM: leaf-wise tree growth
This chapter assumes you know how gradient boosted trees add trees to an ensemble. It also assumes you know what a split gain is, and you can read the histogram chapter's idea that LightGBM scores splits on binned feature values. You need basic Python and scikit-learn.
Two ways to grow a tree
A decision tree starts as one leaf holding all training rows and grows by splitting leaves. The growth strategy decides which leaf to split next.
- Level-wise (depth-wise) growth splits every leaf at the current depth before moving down. The tree stays balanced. XGBoost's default
depthwisepolicy and classic implementations work this way. - Leaf-wise (best-first) growth looks at all current leaves and splits the one whose best split reduces the loss the most. LightGBM uses this strategy.
With the same number of leaves, leaf-wise growth reaches a lower training loss. It spends splits where the loss is highest and skips leaves that are already nearly pure. The cost is that the tree can become lopsided, with some branches going deep.
| Property | Level-wise | Leaf-wise (LightGBM) |
|---|---|---|
| Leaf chosen for the next split | Every leaf at the current depth | The one leaf with the highest gain |
| Tree shape | Balanced | Often unbalanced |
| Main size control | `max_depth` | `num_leaves` |
| Training loss at equal leaf count | Higher | Lower |
| Overfitting risk on small data | Lower | Higher |
The growth loop
LightGBM grows each tree as follows.
- Start with the root as the only leaf.
- For every leaf, find the best split using the feature histograms and record its gain.
- Pick the leaf with the largest gain and split it into two children.
- Compute the best split for the two new children. The other leaves keep their stored gains.
- Stop when the tree has
num_leavesleaves, or when no leaf has a valid split.
A split is valid only if both children satisfy min_data_in_leaf (alias min_child_samples) and min_sum_hessian_in_leaf. The gain must also exceed min_gain_to_split. The max_depth limit, if set, also blocks splits.
Because only the two new children need fresh gain calculations, each step costs little. The histograms from the previous chapter keep that search cheap.
Why num_leaves is the main complexity control
In level-wise libraries, max_depth fixes the size: a tree of depth d has at most 2^d leaves. In a leaf-wise tree, depth no longer determines size. A tree with 31 leaves might be 5 levels deep if balanced, or 20 levels deep if one branch keeps winning the gain contest. So num_leaves is the primary knob. The default is 31.
If you do set max_depth, keep num_leaves below 2^max_depth. With max_depth=4, the tree can have at most 16 leaves. A setting of num_leaves=64 is then silently capped by the depth limit and has no effect beyond 16.
A common rule of thumb is to start num_leaves well under 2^max_depth and raise it only while validation error keeps improving. More leaves mean more capacity, so the usual pattern is that validation error falls and then rises again.
Seeing the effect
The script below trains three models that differ only in num_leaves. It then reads each model's trees to report the actual depth reached. trees_to_dataframe returns one row per node, and its node_depth column gives each node's depth.
import lightgbm as lgb
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
X, y = fetch_california_housing(return_X_y=True, as_frame=True)
X_train, X_valid, y_train, y_valid = train_test_split(
X, y, test_size=0.2, random_state=0
)
for num_leaves in (7, 31, 255):
model = lgb.LGBMRegressor(
n_estimators=2000,
learning_rate=0.05,
num_leaves=num_leaves,
min_child_samples=20,
verbose=-1,
)
model.fit(
X_train,
y_train,
eval_set=[(X_valid, y_valid)],
eval_metric="rmse",
callbacks=[lgb.early_stopping(stopping_rounds=50, verbose=False)],
)
nodes = model.booster_.trees_to_dataframe()
used = nodes[nodes["tree_index"] < model.best_iteration_]
print(
f"num_leaves={num_leaves:>3} "
f"trees={model.best_iteration_:>4} "
f"deepest node={used['node_depth'].max():>2} "
f"valid RMSE={model.best_score_['valid_0']['rmse']:.4f}"
)The filter on tree_index matters. Early stopping keeps the trees that were trained after the best iteration inside the booster, and predict uses only the best ones by default. Without the filter, you would count nodes that the model does not use.
When you run it, expect these patterns. Small num_leaves needs many more trees. Large num_leaves converges in few trees and reaches a depth well beyond log2(num_leaves). The validation RMSE does not improve forever as num_leaves grows.
Overfitting and the controls that counter it
A leaf-wise tree can carve out a tiny leaf for a handful of noisy rows, because splitting that leaf still has the highest available gain. These parameters limit that behavior.
min_data_in_leaf(default 20) blocks splits that leave fewer rows in a child. It is the most effective guard on small datasets. For large datasets, values in the hundreds or thousands are common.max_depthcaps how deep any branch can go. Use it as a safety net, for example 8 to 12 withnum_leavesof 63 or more.lambda_l2shrinks leaf values and reduces the influence of small leaves.min_gain_to_splitrejects splits whose gain is below a threshold.learning_ratewith early stopping, covered in a later chapter, decides how many trees are used.
Failure modes to watch for
- Deep, thin branches. A feature with a strong but narrow signal can produce one very deep branch. Check
node_depthas above. If the maximum is far beyondlog2(num_leaves), setmax_depth. - Ignored
num_leaves. Settingnum_leavesabove2^max_depthhas no effect, as described earlier. - Tuning the wrong parameter. Copying a
max_depth=6recipe from a level-wise library does not give LightGBM the same capacity. Translate it to anum_leavesvalue and tune from there. - Comparing models by leaf count alone. A leaf-wise tree with 31 leaves is more expressive than a level-wise tree with 31 leaves. Compare libraries by validation error under early stopping, not by matching size settings.
Exercise
A LightGBM model is trained with numleaves=64 and maxdepth=4. What is the maximum number of leaves per tree, and why? Name one parameter you would raise to stop a leaf-wise tree from isolating tiny groups of rows.
Show answer
At most 16 leaves, because a tree of depth 4 can hold at most 2^4 = 16 leaves, so the depth limit overrides numleaves=64. To stop tiny leaves, raise mindatainleaf (alias minchildsamples), which blocks any split that would leave fewer rows than that in a child.
Exercise
Why does leaf-wise growth reach a lower training loss than level-wise growth when both produce trees with the same number of leaves?
Show answer
Leaf-wise growth always splits the leaf with the highest gain, so each split removes as much loss as possible. Level-wise growth must also split leaves at the current depth that offer little gain, which spends some of the leaf budget on weak splits.