Sub topic 3
LightGBM: Histogram-Based Split Finding
This chapter assumes you know how gradient boosted trees work. That means each new tree fits the gradients of the loss, and a leaf's value comes from summed gradients and Hessians. It also assumes you can read basic NumPy and pandas code. Here you will see how LightGBM finds splits quickly by replacing raw feature values with small integer bins.
Why exact split finding is slow
A tree learner must pick, for each node, the feature and threshold that give the best gain. The exact method works like this:
- Sort the rows by each feature.
- Scan the sorted values, accumulating gradient sums.
- Evaluate a candidate split at every distinct value.
With n rows and d features, each node costs roughly O(n × d) for the scan, plus the sorting, which can be amortized. Memory is also a problem. The sorted order and the 32-bit or 64-bit float values must be kept for every feature.
LightGBM avoids both costs by discretizing each feature once, before training.
Binning features into histograms
When you build a lgb.Dataset, LightGBM converts every numeric feature into integer bin indices. By default there are at most 255 bins per feature (max_bin=255).
- It looks at a sample of rows (
bin_construct_sample_cnt, default 200000) to choose bin boundaries. - Boundaries follow the data distribution, so bins hold roughly equal numbers of rows. They are not equal-width.
- A feature with fewer distinct values than
max_bingets one bin per value. min_data_in_bin(default 3) stops tiny bins from forming around rare values.- Missing values get their own bin, and zero is kept in a bin of its own so sparse data stays cheap to process.
Because the indices fit in one byte when max_bin ≤ 255, the training data takes much less memory than raw floats. The raw values are not needed again. At prediction time, the split thresholds stored in the model are real feature values taken from the bin boundaries.
Finding the best split from a histogram
For one node and one feature, LightGBM makes a single pass over the node's rows. For each row it adds the row's gradient g and Hessian h to the bin the row falls in. The result is a histogram with, per bin, a gradient sum, a Hessian sum and a row count.
The split search then scans the bins, not the rows. Candidate splits sit between adjacent bins. With the running sums G_L, H_L on the left, G_R, H_R on the right, and regularization λ (lambda_l2), the gain is:
gain = G_L² / (H_L + λ) + G_R² / (H_R + λ) − (G_L + G_R)² / (H_L + H_R + λ)
The cost per node and feature becomes O(rows_in_node) to fill the histogram and O(max_bin) to scan it. The scan is tiny next to the fill when the node has many rows.
The following example does this by hand for one feature, using squared error, where the gradient is prediction − y and the Hessian is 1.
import numpy as np
rng = np.random.default_rng(0)
n = 10_000
x = rng.normal(size=n)
y = (x > 0.3).astype(float) + rng.normal(scale=0.1, size=n)
# 1. Quantile binning: 16 bins with roughly equal row counts.
max_bin = 16
edges = np.quantile(x, np.linspace(0, 1, max_bin + 1)[1:-1])
bins = np.searchsorted(edges, x, side="right") # values 0..max_bin-1
# 2. Gradients and Hessians for squared error, starting from prediction 0.
grad = 0.0 - y
hess = np.ones(n)
# 3. One pass over the rows builds the histogram.
G = np.bincount(bins, weights=grad, minlength=max_bin)
H = np.bincount(bins, weights=hess, minlength=max_bin)
# 4. Scan the bins, not the rows.
lam = 1.0
G_left, H_left = np.cumsum(G)[:-1], np.cumsum(H)[:-1]
G_tot, H_tot = G.sum(), H.sum()
G_right, H_right = G_tot - G_left, H_tot - H_left
gain = (
G_left**2 / (H_left + lam)
+ G_right**2 / (H_right + lam)
- G_tot**2 / (H_tot + lam)
)
best = int(np.argmax(gain))
print("best bin boundary index:", best)
print("threshold: x <", round(float(edges[best]), 3))
print("gain:", round(float(gain[best]), 1))The true boundary is 0.3. The printed threshold lands on the nearest quantile edge, which is close to 0.3 but not exactly it. That gap is the price of discretization.
The histogram subtraction trick
After a node splits, both children need histograms. LightGBM builds the histogram only for the child with fewer rows. It gets the sibling's histogram by subtraction:
histogram(larger child) = histogram(parent) − histogram(smaller child)
This works because the gradient, Hessian and count sums are additive. The subtraction costs O(max_bin) per feature instead of a pass over the larger child's rows. This roughly halves the histogram work at each level, and the saving is largest when splits are unbalanced.
Controlling the bins
The binning parameters belong to the Dataset, not to the training call. Binning happens when the dataset is constructed, so changing max_bin afterward has no effect on an already constructed dataset.
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
)
params = {
"objective": "regression",
"metric": "rmse",
"learning_rate": 0.05,
"num_leaves": 31,
"verbose": -1,
}
for max_bin in (255, 63, 15):
train_set = lgb.Dataset(X_train, label=y_train, params={"max_bin": max_bin})
valid_set = lgb.Dataset(X_valid, label=y_valid, reference=train_set)
booster = lgb.train(
params,
train_set,
num_boost_round=1000,
valid_sets=[valid_set],
callbacks=[lgb.early_stopping(50, verbose=False)],
)
rmse = booster.best_score["valid_0"]["rmse"]
print(f"max_bin={max_bin:>3} best_iter={booster.best_iteration:>4} rmse={rmse:.4f}")Expect the validation RMSE to change only slightly between 255 and 63 bins. It usually degrades at very small values like 15, because the bins can no longer isolate useful thresholds.
Trade-offs and edge cases
| Choice | Effect |
|---|---|
| Larger `max_bin` | Finer thresholds, slower fill and scan, more memory |
| Smaller `max_bin` | Faster, less memory, acts as mild regularization, can miss sharp thresholds |
| Larger `min_data_in_bin` | Fewer bins on sparse or rare-value features |
- Validation sets need
reference. The validationDatasetmust reuse the training bin boundaries. Passreference=train_set. The scikit-learn API does this for you througheval_set. - Bins come from a sample. On very large data, boundaries are computed from
bin_construct_sample_cntrows. Rare extreme values may share a bin with their neighbors. - Quantile bins can hide heavy tails. If a feature has a long tail, many extreme values may fall into one top bin, and you cannot split inside it.
- Dense integer features lose nothing. An integer feature with fewer than 255 distinct values keeps one bin per value, so binning is lossless for it.
- Ties and monotonicity. Two values in the same bin are always treated the same by a given tree, even if they differ slightly.
Summary of the cost model
| Step | Exact method | Histogram method |
|---|---|---|
| One-time setup | Sort values per feature | Bin values per feature |
| Per node, per feature | Scan every row | Fill histogram, then scan bins |
| Sibling node | Repeat full work | Subtract from parent |
| Memory per value | 4 to 8 bytes | 1 byte when `max_bin ≤ 255` |
Exercise
A node has 200000 rows and 100 features, and max_bin=255. It splits into children with 20000 and 180000 rows. Roughly how many rows must LightGBM read to build both children's histograms, and how does the other child's histogram get computed?
Show answer
LightGBM reads only the 20000 rows of the smaller child for each of the 100 features. The 180000-row child's histogram is computed as the parent histogram minus the smaller child's histogram. That is a per-bin subtraction of at most 255 values per feature, with no pass over the 180000 rows.
Exercise
You train with lgb.Dataset(X_train, y_train) and lgb.Dataset(X_valid, y_valid), without reference. Why can this be a problem, and how do you fix it?
Show answer
The validation set would be binned with its own boundaries, which differ from the training boundaries the trees were built on. Bin indices would not match the learned splits. Fix it by passing reference=train_set when creating the validation Dataset, so it reuses the training bin boundaries.