LightGBM and CatBoost: histograms, sampling and ordered boosting
Study the two major responses after XGBoost. LightGBM addresses computational cost through histograms and subtraction, leaf-wise growth, GOSS (gradient-based sampling) and EFB (exclusive feature bundling). CatBoost addresses statistical bias: label leakage in target statistics and prediction shift from data reuse, solved with ordered statistics and ordered boosting on symmetric trees.
After this lesson you can
- Implement histogram split search using sibling-histogram subtraction.
- Compare level-wise and leaf-wise growth and relate num_leaves to max_depth.
- Explain GOSS and prove that reweighting small-gradient samples keeps gradient sums unbiased.
- Explain EFB as a graph-coloring problem solved greedily.
- Identify label leakage in naive target statistics and prediction shift, and explain how ordered statistics and boosting avoid them.
- Describe symmetric trees and their effect on regularization and inference speed.
Before you start
Motivation: two bottlenecks after XGBoost
In the previous lesson you derived XGBoost from its objective: each round computes and , each leaf receives the optimal weight , and each split is judged by second-order gain. This is the core of Newton boosting, retained by both libraries in this lesson. They change something else.
LightGBM (Ke et al., NeurIPS 2017) addresses cost. Its paper starts with an observation about histogram algorithms: building histograms costs and searching them for a split costs ; since there are far fewer bins than data, construction dominates. To go faster one of these factors must change, and the paper proposes a technique for each: GOSS reduces rows by gradient-guided sampling and EFB reduces columns by bundling sparse features never nonzero together. Two design choices are added, which the paper does not claim as original contributions but the library made standard: histograms with subtraction (the histogram algorithm is attributed to earlier work) and leaf-wise tree growth (cited to Shi’s 2007 thesis). The paper’s abstract claims everything together speeds training by “over 20 times” with nearly the same accuracy.
CatBoost (Prokhorenkova et al., NeurIPS 2018) addresses a statistical bias nobody had formalized. When a categorical feature is replaced by its category’s target mean, a row uses its own label to encode itself: leakage. Boosting as a whole has a subtler version: round gradients are computed using a model that has already seen those same rows, so they differ from gradients for a new example. The paper calls this prediction shift, proves it exists in a simple case and corrects it with one principle, ordering: each row may use only information from rows preceding it in a random permutation.
The answers are complementary: one concerns fast computation of the same gain, the other which gradients and encodings deserve to enter it. By the end you will have implemented key pieces from scratch (histograms with subtraction, leaf-wise growth, GOSS, EFB, ordered statistics), numerically reproduced the prediction-shift theorem, and measured both libraries on Amazon, the high-cardinality categorical dataset where the CatBoost paper finds the largest difference between encodings.
Histograms: discretize once
The exact split search you built in the previous lesson sorts each feature’s values at each node, or keeps them presorted in blocks. The alternative already encountered as tree_method="hist" is simpler: discretize each feature once before training and thereafter work only with bin number.
There are three immediate gains. No sorting: building the histogram is one pass summing by row, and choosing the split is a cumulative sum over cells. Memory falls: with 255 bins each value fits in one byte (uint8) rather than eight for float64; in the lab’s first cell a matrix goes from 1250 KiB to 156 KiB. And candidate splits are the same at all nodes, simplifying distribution among threads and machines. The price is that a threshold can only fall at a bin boundary. Boundaries are chosen so each bin has similar data count (our implementation uses quantiles), like global candidates in XGBoost approximate search but without Hessian weighting. With 255 bins accuracy loss is usually negligible: in the lab test squared error is with exact search and with 255 bins, degrading only with very few bins ( with 15 and with 4).
The algorithm is not LightGBM’s: the paper attributes it to earlier work and notes that pGBRT and XGBoost already implemented it. LightGBM added engineering making it cheap at each node.
The subtraction trick
Histograms are additive: if a node with rows splits into , each parent cell is the sum of the children’s, , and likewise for and , because each row falls in exactly one child. The parent histogram is already computed from the previous step, so build one child’s and obtain the other by cellwise subtraction in operations, without touching its rows. Build the smaller child’s. LightGBM documentation summarizes this: only one leaf’s histogram must be built, the one with less data than its neighbor.
Proof
(1) Splitting a node with rows builds a histogram of rows. Nodes split on the same level have disjoint row sets, so their sum to at most and what is built to at most . Summing the root and split levels yields . Direct construction scans rows per split, at most per level. (2) Fix a row. It is scanned at the root and afterward only when it falls in the smaller child of a split. Every time, its node size falls from to at most . Starting at and never below one row, this can happen only times.
∎The second bound matters for leaf-wise growth below, where trees can be very deep and unbalanced: depth does not bound cost, but the logarithm does. In the lab, a 63-leaf tree of depth 9 on rows scans rows building both children and with subtraction, below bound . Subtraction also has a numerical cost: in floating point is not exactly the direct sum of , but the difference is on the order of rounding ( in the lab), and integer counts are exact.
Notice two things. With , the smaller child has 9 of 40 samples and subtraction takes 17 operations (9 additions and 8 bin subtractions) instead of 40. With , children are nearly equal (19 and 21 samples): fewer than half the rows are scanned, as the theorem guarantees in the worst case, and 8 subtractions raise the total to 27. Subtraction cost depends on bins, not rows: with 40 samples and 16 bins, subtracting cells matters, but with thousands of rows per node it is negligible. The trick pays more for larger nodes near the top of the tree, where almost all work happens.
Leaf-wise growth
Original XGBoost grows trees level-wise: split all nodes at one level before descending to the next, up to max_depth. LightGBM grows leaf-wise: at each step split the leaf anywhere in the tree whose best split has greatest gain, until num_leaves leaves. This is Shi’s (2007) best-first strategy, the same idea as greedy best-first search applied to tree construction.
With the same leaf budget, leaf-wise growth spends each split where loss decreases most, and LightGBM documentation summarizes that, with fixed leaf count, leaf-wise algorithms tend to achieve lower loss than level-wise ones. “Tend” is right: both are greedy and myopic, and a low-gain split made obligatorily by level-wise growth can prepare two good splits leaf-wise growth misses. The price is shape: a level-wise tree with leaves has depth , and a leaf-wise tree can reach depth if it repeatedly splits the same branch. Deep branches isolate small row groups, exactly what is needed to overfit small data.
This gives the relationship between the parameters. A depth- tree has at most leaves, so with max_depth fixed, num_leaves above adds nothing. And if, with max_depth , num_leaves is and all nodes in the first levels admit valid splits, leaf-wise growth ends in the same tree as level-wise: a node’s best split depends only on its rows, not visit order, so splitting all nodes in the first levels gives the same result in any order. You will verify this in the lab: with 64 leaves and max_depth , both policies give identical errors. LightGBM’s tuning guide gives max_depth : a level-wise tree of that depth can work well, num_leaves 127 can overfit, and 70 or 80 can be more accurate. Default num_leaves is 31, with max_depth (unlimited) and min_data_in_leaf , as the local lab shows.
Look at depth in the corners of both panels. With 12 leaves and 200 samples, leaf-wise already has depth 5, one more than a complete level-wise tree permits, and lower validation error ( versus ); its best validation arrives earlier, at 6 leaves (), while level-wise needs 21 to reach . With 800 samples the advantage remains ( with 8 leaves versus with 32). Now lower min_data_in_leaf to 1 with 100 samples and advance to 48 leaves: leaf-wise keeps splitting noise to depth 13, training error falls to and validation rises to , above level-wise. This is LightGBM’s first common error on small datasets, and why documentation emphasizes max_depth and min_data_in_leaf as brakes on leaf-wise growth. Today the strategy is not exclusive to LightGBM: scikit-learn’s HistGradientBoostingClassifier grows leaf-wise with default max_leaf_nodes=31, and XGBoost offers grow_policy="lossguide".
GOSS: sample rows without losing gain
Subsampling rows each round was already known: Friedman’s stochastic gradient boosting trains each tree on a random data fraction. LightGBM observes that rows contribute differently to gain. A row with small is already well fitted; one with large is what the round’s tree must correct. Randomly discarding treats both alike. GOSS (gradient-based one-side sampling) samples only one side: it keeps all large-gradient rows and subsamples small ones.
The paper has a small inconsistency worth knowing: algorithm 2 takes rows from the remainder, as above, but section 3.2’s text says has size . Under the second reading the correct factor would be , not . Implementation follows the algorithm: in goss.hpp, small-row count is cnt * other_rate and multiplier (cnt - top_k) / other_k, i.e., .
Proof
is determined by gradients, so is not random. is a simple random sample of rows out of in , so each enters with probability . Writing and taking expectations gives . Adding ‘s part gives , likewise for . Factor is the weight of a Horvitz–Thompson estimator: each sampled row represents rows in its stratum.
∎Unbiased sums do not make gain unbiased. Gain is , a nonlinear function, and by Jensen’s inequality : with any sampling estimated gain tends to be optimistic, increasingly so as sum variance increases. Thus whether GOSS beats uniform sampling depends on that variance. As both are simple random samples without replacement, it can be calculated exactly.
Proof
For a simple random sample of elements from a population of , the total estimator has variance , where is population sample variance. In uniform sampling, and : . In GOSS, ‘s part is fixed and ‘s is that estimator with and : . The ratio is , less than 1 exactly under the stated condition.
∎The threshold is intuitive. If , GOSS is uniform sampling ( and threshold 1). With and , LightGBM defaults, GOSS wins if removing the 20% highest-gradient rows leaves variance under of the total. This happens when gradients are concentrated: a few poorly fitted rows and a mostly solved majority. When all are similar, as in the first classification round with for everyone, removing the top reduces nothing and GOSS loses because it samples the remainder at rate below uniform’s . The paper gives a probability bound on gain error (theorem 3.2) and from it a sufficient condition to beat random sampling, in terms of maximum gradient inside and outside ; the formula above is exact for sums.
In the initial state (, , ), large gradients are examples misclassified near boundary , and the 60 retained rows sum to 65% of . The split signal, step , is instead spread over many small negative gradients: the model predicts slightly less than it should there. GOSS’s histogram is clearly narrower than uniform’s (deviation versus ), and both means ( and ) lie right of exact gain : Jensen optimism, greater for the wider estimator. With , all are almost equal and the order reverses. The lab cell quantifies this with and the theorem’s formula: with , standard deviation of is for GOSS and for uniform; with , versus ; with but , set is too small to catch large gradients and GOSS loses again, versus . Deviations measured in 3,000 batches agree to within 3%.
Real implementation has three details absent from the paper and found in goss.hpp. It does not sample for the first iterations, because gradients are not concentrated initially (precisely case ). It sorts by , not . And it picks small rows by sequential sampling with adjusted probability to obtain exactly other_k. In LightGBM 4 enable it with data_sample_strategy="goss", default top_rate and other_rate .
What about final accuracy? The paper compares GOSS with Friedman subsampling on LETOR (table 4, NDCG@10 with early stopping): at total fraction 0.1, versus ; at 0.4, versus ; GOSS wins at all tested fractions. For speed, comparing LightGBM with and without GOSS (table 2), the paper attributes nearly 2× speedup to GOSS using 10%–20% of data: it is not linear in fraction because computing gradients and predictions still costs the same. You will measure it with the library in two noise regimes in the local lab.
EFB: bundle features that do not coincide
GOSS reduces rows. EFB (exclusive feature bundling) reduces columns, relying on something common in large tabular data: sparsity. A one-hot categorical creates many columns of which only one is 1 in each row; count or text features are almost always zero. Two columns never simultaneously nonzero can be stored in one, offsetting the second’s bins so they do not mix with the first. The joint histogram contains both.
Proof
Reduce graph coloring, which is NP-hard (even its three-color decision version is NP-complete). Given graph , construct data with one row per edge and one feature per vertex: feature is 1 in the row for edge if is an endpoint of , otherwise 0 (each feature is a row of ‘s incidence matrix). Two features are simultaneously nonzero in some row if and only if edge exists. Thus a conflict-free bundle is exactly an independent set of , a partition into bundles is a coloring with colors and the minimum bundle count is the chromatic number. A polynomial algorithm for optimal bundling would solve coloring.
∎Since the optimum is intractable, LightGBM uses the greedy paradigm (algorithm 3): build a conflict graph with edge weights equal to conflicting-row counts, sort features by descending degree and place each in the first bundle whose conflict count plus its conflicts with that bundle does not exceed ; if none fits, open a new one. With this is classical greedy coloring. Three nuances:
- No constant approximation guarantee. The paper claims greedy gives “a constant approximation ratio,” but this is false for coloring in general: greedy guarantees at most colors, with maximum degree, and approximating chromatic number within factor is NP-hard for every (Zuckerman, 2007). Greedy does work well on real data because one-hot conflict graphs have considerable structure.
- Tolerated conflicts. Many features are not exactly exclusive, but nearly so. If a fraction of each bundle’s rows can conflict, the paper bounds the training accuracy effect by . In conflicting rows the merged value can store only one feature (the last in the bundle in algorithm 4).
- Sort without building the graph. The graph costs , too much with millions of features; the paper proposes sorting by nonzero count, resembling degree because more nonzeros mean more conflict probability.
With EFB, histogram construction cost falls from to . In paper table 2, adding EFB to LightGBM without GOSS lowers iteration time from 6.07 s to 0.71 s on Allstate (12 million rows, 4228 sparse features) and 39.85 s to 6.33 s on KDD10; on LETOR with 136 dense features it barely changes (0.49 s versus 0.46 s). This is expected: without sparsity there is nothing to bundle.
With greedy uses three bundles and fewer are impossible: C, B3 and A3 are simultaneously nonzero in the first row, forming a graph triangle needing three colors. Notice also that greedy does not necessarily join indicators of one category despite never coinciding: A4 ends with B3 because that is its first compatible bundle in order. Raising accepts bundles with conflicting rows, lowers bundle count and produces red borders: rows where the merged value lost a feature. This speed–fidelity tradeoff is controlled by in the library.
Categorical features in LightGBM
A categorical with levels has ways to split levels into two groups. In regression and binary classification not all need testing: Fisher’s (1958) classical result, seen as categorical splits, says the best split lies among the respecting the ordering of target means by level. LightGBM applies the second-order version at each node: sort levels by of node rows (with cat_smooth added to Hessian) and scan as if numeric, at cost .
This is a good algorithm with a clear risk: ordering uses gradients of the same rows later split. With many levels and few rows per level, ordering by puts levels with chance extreme gradients first and the split finds a separation that does not generalize. This is the same leakage mechanism as target statistics below, applied within each node. LightGBM limits it with several parameters whose defaults the local lab prints: max_cat_to_onehot (with 4 or fewer levels, one level versus rest), cat_smooth , cat_l2 (specific L2 regularization for categorical splits), min_data_per_group (minimum rows per group of levels), and max_cat_threshold (limits tested cut points in the ordering and hence level-group size). The CatBoost paper adds two criticisms: storing each level’s leaf costs memory, and LightGBM groups tail levels together, losing information.
The opposite error is also common: not declaring the categorical. If level codes are passed as integers, LightGBM treats them as numeric and can only split at thresholds of an arbitrary order (identifiers), unrelated to the target. Deep trees compensate for few levels; not for thousands. You will measure this on Amazon.
CatBoost, the problem: label leakage
Target statistics
High-cardinality categoricals are everywhere: users and ads in click prediction, resources and managers in Amazon, issuers, sectors and counterparties in credit and signal models you will build in quantitative finance. An effective way to bring them into a tree is replacing each level with a number summarizing its category’s target. You saw this in categorical encoding as target encoding; CatBoost calls it a target statistic (TS). Micci-Barreca’s (2001) classical version is the mean smoothed toward a prior:
with the prior (usually global mean of ), its weight, and the set of rows used to encode row . Naive (greedy) TS uses all: . Here is the leak: contains .
The paper takes this to an extreme. Suppose all levels are distinct (an identifier) and everywhere: the feature is useless. In training, each row is the only one of its level and , so one split at classifies perfectly. In test all levels are new, and the model is right half the time. The distribution of conditional on differs between training and test, a conditional shift, and the paper formulates the property that should hold:
P1. : the relationship between encoding and label is the same for a test example as a training example.
Alternatives are judged by P1 and a second property, P2: use all data both to calculate TS and to train.
- Holdout: compute TS with part of the data and train with the rest. Satisfies P1 and violates P2.
- Leave-one-out: . It seems to solve it but does not. If the categorical is constant and there are ones, : rows with receive a slightly lower value than those with , and threshold separates them all. Within each level the value reveals the label.
- Cross-validation ( folds, the cross-fitting of causal inference): each row is encoded with other folds. It does not see its label and uses all data, although each encoding comes from fraction of them.
With naive encoding and 300 levels (about 3.3 rows per level), a row’s own label weighs in its mean: training rows with shift right of those with , unlike test. The model gives a pure-noise feature 64% of gain, and test loss () moves away from Bayes () while training falls to . With 1000 levels it is worse (87% and ); with 10 levels, 100 rows per level dilute the own label and leakage is barely visible (10%). Now switch to leave-one-out with 10 levels: each row’s value depends on its label by , yet the tree learns that tiny shift level by level because 32 bins separate the 20 distinct values: the categorical gets 81% of gain and test loss reaches . This is precisely the frequent-category failure described in the paper. With cross-fitting and ordered encoding, training resembles test, the categorical gets what any noise feature can gain (8%–17% depending on ), and test loss is within of Bayes.
The lesson is general and connects to data leakage: a feature constructed using its own row’s label is future information. In causal inference it is analogous to conditioning on a post-treatment variable; in finance, to look-ahead bias.
Prediction shift
The paper goes further, its main contribution. Naive TS is a small statistical model (a mean per level) trained on the same rows to which it is applied. But boosting does the same: model was trained on all rows, and round gradients are computed on those same rows. The paper describes a chain of shifts:
- the distribution of on a training row (counting randomness in other data) differs from on a new example;
- therefore tree fitted to those gradients is biased relative to the tree fitted with new-data gradients;
- and that worsens generalization of .
It calls this prediction shift and proves it in the simplest possible case.
Term covers the exponentially unlikely case of a leaf with no examples. The proof idea, in appendix A, fits in two lines. With the count of rows with , the first stump is . On a new example, . On a training row, the row itself is inside : if it has , it raises its leaf’s fraction, and the paper obtains . Training residuals are shrunk toward zero, and the second stump fits them and inherits shrinkage. Bias is inversely proportional to and proportional to : it matters for small datasets and strong relationships. In the lab you reproduce it by Monte Carlo: with , and , measured bias over is versus the theorem’s (difference within Monte Carlo error), and it disappears with two independent samples.
Notice what the theorem says and does not. It does not say the model is bad: with bias is 0.5% of . It says reusing data to compute gradients has a systematic bias like naive TS, and its natural remedy is the same: do not use a row’s label to calculate what is asked of that row.
CatBoost, the solution: ordering
With unlimited data the solution would be trivial: each round uses a fresh sample. CatBoost simulates this with one sample using a random permutation of rows, an “artificial time” like online algorithms: each row can use only history, preceding rows.
Ordered target statistics
does not enter , and is calculated from rows as foreign to row as training is to a test example: hence it satisfies P1 according to the paper and uses all data (P2). The cost is variance: early permutation rows have little history and TS is nearly the prior. CatBoost reduces it with different permutations in different boosting steps. This is online encoding of a data stream: each row’s value is what was known about its category just before seeing it.
Ordered boosting
For gradients the same principle costs more. For row ‘s residual to be unshifted, the model computing it cannot have seen row . The paper’s algorithm 1 follows this literally: maintain supporting models , where trains only on the first permutation rows, and row ‘s residual uses , which has not seen it. This multiplies cost and memory by , so is not viable as-is.
The last point is easy to miss: ordering decides which splits are made, not leaf values of the predicting model. The lab shows why this distinction matters. In the theorem’s example ordered residuals (each row with a first stump trained only on predecessors) have exactly the mean for a new example, for rows with , while classical ones are shrunk. But fitting the second stump to these ordered residuals and adding it to the first stump trained on all data does not eliminate final bias: it reverses sign and is similar in size, because the second stump corrects supporting models that are not the first stump ending up in the model. The paper does not claim the final model is unbiased; it claims the gradients constructing each tree are unshifted, and measures the practical effect.
It measures honestly: in table 3, Plain worsens logistic loss relative to Ordered by 1.1% on Adult and 3.9% on Internet, the two smallest datasets (under 40,000 training rows), but improves it on Amazon () and Kick (), and Click and Churn differ by hundredths of a point. When subsampling datasets (figure 2), Ordered’s advantage grows as the fraction shrinks. Time cost: on Epsilon, 1.9 s per tree versus 1.1 s for Plain (about 1.7× slower). CatBoost documentation says Ordered often gives better quality on small datasets but can be slower; on CPU the default is Plain, and on GPU Ordered with up to 50,000 objects.
Two more pieces complete the algorithm. TS and boosting use the same permutation (): if different, row ‘s label could enter model through another row’s TS. CatBoost also greedily builds categorical combinations: at each tree split, concatenate categoricals (and combinations) already used in that tree with all others and convert to TS on the fly, capturing interactions like user by ad topic. According to the paper, moving from no combinations to pairs improves logistic loss 1.86% on average (up to 11.3%), and allowing triples 2.04%.
Symmetric trees
The final ingredient is tree type. CatBoost uses symmetric trees (oblivious, or decision tables): all nodes at a level apply the same split.
The index formula comes from Dorogush, Ershov and Gulin (2018), describing CatBoost’s evaluator: first binarize all used features, store bits of all examples in a contiguous vector and calculate each tree’s index using sums of powers of two. Three consequences:
- Fast inference. The bits are independent comparisons, with no mutually dependent conditional branches, so they can be computed in parallel for many examples (vector instructions) and the leaf read directly from a table. In that paper’s table 3, evaluating 8000 trees on Epsilon with one thread costs 2.4 s for CatBoost, 78 s XGBoost and 122 s LightGBM; authors summarize about 25 and 60 times faster. These are 2018 figures for one configuration: the robust point is the cause, not factor.
- Regularization. A depth- symmetric tree has leaves but only chosen splits, versus in a general tree. It is a much smaller function family: it cannot refine only the branch containing signal. The CatBoost paper says such trees are balanced and less prone to overfit.
- One search per level. During construction each candidate is scored by summing its effect across all leaves at that level: one split search per level, not per node.
Move the level-0 threshold: the vertical boundary crosses the whole plane because the same split applies on both branches. A general tree could refine only where changes quickly; a symmetric one cannot. When two levels test the same feature, some bit combinations are impossible ( and simultaneously in the initial state): those leaves exist in the table but no point reaches them, so the eight-leaf tree has only six regions. With dozens of features repetition is an algorithm choice rather than necessity, but it illustrates family rigidity: every split divides all regions at once.
Implementation from scratch
Now build the pieces. Cells run in your browser and share a session: each can use definitions from previous cells.
Histograms and sibling subtraction
First discretization (quantile boundaries, or midpoints with few distinct values), histograms for all three quantities and all features at once using one np.bincount (bin of feature goes to cell ), and the subtraction check.
import numpy as np
np.seterr(divide="ignore", invalid="ignore")
def umbrales(x, max_bin=255):
"""Fronteras de los cubos de una variable: puntos medios si hay pocos valores distintos, cuantiles si no."""
u = np.unique(x)
if len(u) <= max_bin:
return (u[:-1] + u[1:]) / 2
return np.unique(np.quantile(x, np.arange(1, max_bin) / max_bin))
def discretizar(X, max_bin=255, fronteras=None):
"""Cubo de cada valor (regla x <= frontera a la izquierda), en uint8: un byte por celda."""
if fronteras is None:
fronteras = [umbrales(X[:, k], max_bin) for k in range(X.shape[1])]
Xb = np.column_stack([np.searchsorted(f, X[:, k], side="left") for k, f in enumerate(fronteras)])
return Xb.astype(np.uint8), fronteras
def histogramas(Xb, g, h, idx, B):
"""Histogramas de gradiente, hessiana y recuento de las filas idx, para todas las variables: forma (3, d, B)."""
d = Xb.shape[1]
cubo = (Xb[idx].astype(np.int64) + np.arange(d) * B).ravel()
Gh = np.bincount(cubo, np.repeat(g[idx], d), d * B)
Hh = np.bincount(cubo, np.repeat(h[idx], d), d * B)
Ch = np.bincount(cubo, minlength=d * B).astype(float)
return np.stack([Gh, Hh, Ch]).reshape(3, d, B)
rng = np.random.default_rng(0)
n, d = 20000, 8
X = rng.normal(size=(n, d))
Xb, fr = discretizar(X)
g, h = rng.normal(size=n), rng.uniform(0.05, 0.25, n)
padre = histogramas(Xb, g, h, np.arange(n), 256)
izq = X[:, 0] < 0.7
pequeno, grande = np.flatnonzero(~izq), np.flatnonzero(izq)
directo = histogramas(Xb, g, h, grande, 256)
restado = padre - histogramas(Xb, g, h, pequeno, 256)
print("cubos por variable:", [len(f) + 1 for f in fr])
print(f"memoria: float64 {X.nbytes // 1024} KiB, uint8 {Xb.nbytes // 1024} KiB")
print("filas: hijo pequeño", len(pequeno), " hijo grande", len(grande))
print("máx |resta - directo| en G y H:", np.abs(restado[:2] - directo[:2]).max())
print("recuentos idénticos:", np.array_equal(restado[2], directo[2]))The 254 boundaries per feature give 255 bins, fitting in a byte and dividing memory by eight. Subtraction reproduces the larger child’s direct histogram up to rounding and counts exactly.
A minimal LightGBM
Now the tree: leaf-wise growth (or level-wise for comparison), sibling subtraction with the smaller child, num_leaves, max_depth, min_data_in_leaf, and Newton gain with , stored without like LightGBM and scikit-learn. On top is the boosting loop, optional GOSS or uniform sampling and gain importance.
import numpy as np
class Cuadratica:
def grad_hess(self, y, F):
return F - y, np.ones_like(F)
def inicial(self, y):
return float(np.mean(y))
class Logistica:
def grad_hess(self, y, F):
p = 1 / (1 + np.exp(-F))
return p - y, p * (1 - p)
def inicial(self, y):
m = np.mean(y)
return float(np.log(m / (1 - m)))
def valor(self, y, F):
return float(np.mean(np.logaddexp(0, F) - y * F))
class ArbolHist:
"""Árbol de un GBDT por histogramas. politica='hojas' (best-first, como LightGBM) o 'niveles'."""
def __init__(self, num_leaves=31, max_depth=-1, min_data_in_leaf=20, lam=0.0,
min_sum_hessian=1e-3, politica="hojas", restar=True):
self.L, self.D, self.mdl, self.lam = num_leaves, max_depth, min_data_in_leaf, lam
self.msh, self.politica, self.restar = min_sum_hessian, politica, restar
def _mejor(self, hist):
"""Mejor corte a partir del histograma (3, d, B) de un nodo: (ganancia, variable, cubo) o None."""
G, H, C = hist[0, 0].sum(), hist[1, 0].sum(), hist[2, 0].sum()
GL, HL, CL = (np.cumsum(hist[i], axis=1)[:, :-1] for i in range(3))
gan = GL**2 / (HL + self.lam) + (G - GL)**2 / (H - HL + self.lam) - G**2 / (H + self.lam)
ok = (CL >= self.mdl) & (C - CL >= self.mdl) & (HL >= self.msh) & (H - HL >= self.msh)
gan = np.where(ok, gan, -np.inf)
k = int(np.argmax(gan))
if not np.isfinite(gan.flat[k]) or gan.flat[k] <= 0:
return None
return float(gan.flat[k]), *divmod(k, gan.shape[1])
def ajustar(self, Xb, g, h, B):
self.nodos, self.filas_recorridas = [], len(g)
def hoja(idx, hist, prof):
nodo = {"w": -hist[0, 0].sum() / (hist[1, 0].sum() + self.lam), "idx": idx, "hist": hist, "prof": prof}
nodo["mejor"] = self._mejor(hist) if (self.D < 0 or prof < self.D) else None
self.nodos.append(nodo)
return len(self.nodos) - 1
hojas = [hoja(np.arange(len(g)), histogramas(Xb, g, h, np.arange(len(g)), B), 0)]
cola = list(hojas) # orden de anchura, para la política por niveles
while len(hojas) < self.L:
if self.politica == "hojas":
cand = [j for j in hojas if self.nodos[j]["mejor"] is not None]
if not cand:
break
j = max(cand, key=lambda j: self.nodos[j]["mejor"][0])
else:
cola = [c for c in cola if self.nodos[c]["mejor"] is not None]
if not cola:
break
j = cola.pop(0)
nodo = self.nodos[j]
gan, k, b = nodo["mejor"]
idx = nodo["idx"]
a_izq = Xb[idx, k] <= b
il, ir = idx[a_izq], idx[~a_izq]
if self.restar: # solo el hijo pequeño; el grande, por resta
peq = il if len(il) <= len(ir) else ir
hp = histogramas(Xb, g, h, peq, B)
hl, hr = (hp, nodo["hist"] - hp) if peq is il else (nodo["hist"] - hp, hp)
self.filas_recorridas += len(peq)
else:
hl, hr = histogramas(Xb, g, h, il, B), histogramas(Xb, g, h, ir, B)
self.filas_recorridas += len(idx)
nodo.update(var=k, cubo=b, gan=gan, izq=hoja(il, hl, nodo["prof"] + 1), der=hoja(ir, hr, nodo["prof"] + 1))
hojas = [x for x in hojas if x != j] + [nodo["izq"], nodo["der"]]
cola += [nodo["izq"], nodo["der"]]
self.n_hojas = len(hojas)
self.profundidad = max(self.nodos[j]["prof"] for j in hojas)
for nd in self.nodos: # lo que solo hace falta al crecer
del nd["hist"], nd["idx"], nd["mejor"]
return self
def predecir(self, Xb):
out = np.empty(len(Xb))
pila = [(0, np.arange(len(Xb)))]
while pila:
i, idx = pila.pop()
nd = self.nodos[i]
if "var" not in nd:
out[idx] = nd["w"]
continue
a_izq = Xb[idx, nd["var"]] <= nd["cubo"]
pila += [(nd["izq"], idx[a_izq]), (nd["der"], idx[~a_izq])]
return out
def goss(g, a, b, r):
"""GOSS: las a·n filas de mayor |g| con peso 1 y b·n del resto, al azar, con peso (1 - a)/b."""
n = len(g)
orden = np.argsort(-np.abs(g), kind="stable")
elegidas = r.choice(orden[int(a * n):], int(b * n), replace=False)
peso = np.ones(n)
peso[elegidas] = (1 - a) / b
return np.r_[orden[: int(a * n)], elegidas], peso
class MiniLGBM:
def __init__(self, perdida, n_arboles=100, eta=0.1, max_bin=255, muestreo=None, semilla=0, **kw):
self.perdida, self.n_arboles, self.eta, self.max_bin = perdida, n_arboles, eta, max_bin
self.muestreo, self.semilla, self.kw = muestreo, semilla, kw
def ajustar(self, X, y):
Xb, self.fronteras = discretizar(X, self.max_bin)
B = max(len(f) for f in self.fronteras) + 1
r = np.random.default_rng(self.semilla)
self.F0 = self.perdida.inicial(y)
F = np.full(len(y), self.F0)
self.arboles = []
for t in range(self.n_arboles):
g, h = self.perdida.grad_hess(y, F)
if self.muestreo is None or t < int(1 / self.eta): # sin muestreo al principio, como LightGBM
idx, w = np.arange(len(y)), np.ones(len(y))
elif self.muestreo[0] == "goss":
idx, w = goss(g, self.muestreo[1], self.muestreo[2], r)
else: # uniforme: la misma fracción, peso 1/fracción
idx = r.choice(len(y), int(self.muestreo[1] * len(y)), replace=False)
w = np.full(len(y), 1 / self.muestreo[1])
arbol = ArbolHist(**self.kw).ajustar(Xb[idx], (w * g)[idx], (w * h)[idx], B)
F = F + self.eta * arbol.predecir(Xb)
self.arboles.append(arbol)
return self
def margen(self, X):
Xb, _ = discretizar(X, fronteras=self.fronteras)
return self.F0 + self.eta * sum(a.predecir(Xb) for a in self.arboles)
def importancia(self, d):
imp = np.zeros(d)
for a in self.arboles:
for nd in a.nodos:
if "var" in nd:
imp[nd["var"]] += nd["gan"]
return imp / imp.sum()
# comprobación: con menos de 255 valores distintos por variable, la discretización no pierde nada
from sklearn.ensemble import HistGradientBoostingRegressor
rng = np.random.default_rng(0)
n, d = 2000, 5
X = rng.integers(0, 60, size=(n, d)).astype(float)
y = np.sin(X[:, 0] / 8) + 0.03 * X[:, 1] * (X[:, 2] > 30) + rng.normal(0, 0.3, n)
Xp = rng.integers(0, 60, size=(1000, d)).astype(float)
mio = MiniLGBM(Cuadratica(), n_arboles=40, eta=0.1, num_leaves=15, min_data_in_leaf=20, lam=1.0).ajustar(X, y)
ref = HistGradientBoostingRegressor(max_iter=40, learning_rate=0.1, max_leaf_nodes=15, max_depth=None,
min_samples_leaf=20, l2_regularization=1.0, early_stopping=False).fit(X, y)
print("regresión, máx |diferencia| en entrenamiento:", np.abs(mio.margen(X) - ref.predict(X)).max())
print("regresión, máx |diferencia| en puntos nuevos:", np.abs(mio.margen(Xp) - ref.predict(Xp)).max())
print("(hojas, profundidad) de los primeros árboles:", [(a.n_hojas, a.profundidad) for a in mio.arboles[:6]])
# lo mismo en clasificación: pérdida logística, hessianas p(1 - p), margen inicial el logit de la media
from sklearn.ensemble import HistGradientBoostingClassifier
z = 2 * np.sin(X[:, 0] / 8) + 0.05 * X[:, 1] * (X[:, 2] > 30) - 1
yc = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(float)
mio_c = MiniLGBM(Logistica(), n_arboles=40, eta=0.1, num_leaves=15, min_data_in_leaf=20, lam=1.0).ajustar(X, yc)
ref_c = HistGradientBoostingClassifier(max_iter=40, learning_rate=0.1, max_leaf_nodes=15, max_depth=None,
min_samples_leaf=20, l2_regularization=1.0, early_stopping=False).fit(X, yc)
print("clasificación, máx |diferencia de margen| en entrenamiento:", np.abs(mio_c.margen(X) - ref_c.decision_function(X)).max())
print("clasificación, máx |diferencia de margen| en puntos nuevos:", np.abs(mio_c.margen(Xp) - ref_c.decision_function(Xp)).max())HistGradientBoostingRegressor and HistGradientBoostingClassifier are histogram GBDTs growing leaf-wise (their max_leaf_nodes is our num_leaves), with the same leaf weight, gain and min_samples_leaf rule. When each feature has fewer than 255 distinct values, their boundaries are midpoints between consecutive values like ours, so they should build the same trees. They do: in regression differences are on the order of , rounding from scikit-learn storing gradients and Hessians in float32; in classification, on the order of on all training rows. But new classification points show a difference of , with an instructive cause. At a node of tree 30 no row has : bin 30 is empty and splitting at “bin ” or “bin ” separates training data identically with the same gain. Implementations break that tie differently (in ours, sibling subtraction leaves a rounding residual in the empty bin enough to break the tie; building both children directly leaves the bin exactly zero and our tree chooses 29, like scikit-learn), and a new point with in that region falls on different sides. On training the models are the same; where no data exist each implementation decides differently. With 15 leaves trees reach depth 5 or 6, more than the 4 levels of a complete 16-leaf tree.
Exact versus histograms
How much is gained and lost? The same regression, leaf-wise in both cases, with exact search (sorting each feature in each leaf) and histograms of different sizes.
import time
import numpy as np
def corte_exacto(X, g, h, idx, mdl, lam):
G, H, n = g[idx].sum(), h[idx].sum(), len(idx)
mejor = None
for k in range(X.shape[1]):
o = idx[np.argsort(X[idx, k], kind="stable")]
xs = X[o, k]
GL, HL, CL = np.cumsum(g[o])[:-1], np.cumsum(h[o])[:-1], np.arange(1, n)
gan = GL**2 / (HL + lam) + (G - GL)**2 / (H - HL + lam) - G**2 / (H + lam)
gan = np.where((xs[1:] > xs[:-1]) & (CL >= mdl) & (n - CL >= mdl), gan, -np.inf)
j = int(np.argmax(gan))
if gan[j] > 0 and (mejor is None or gan[j] > mejor[0]):
mejor = (float(gan[j]), k, (xs[j] + xs[j + 1]) / 2)
return mejor
def arbol_exacto(X, g, h, num_leaves, mdl, lam):
"""Crecimiento por hojas con búsqueda exacta. Devuelve la función de predicción."""
nodos = []
def hoja(idx):
nodos.append({"w": -g[idx].sum() / (h[idx].sum() + lam), "idx": idx, "mejor": corte_exacto(X, g, h, idx, mdl, lam)})
return len(nodos) - 1
hojas = [hoja(np.arange(len(g)))]
while len(hojas) < num_leaves:
cand = [j for j in hojas if nodos[j]["mejor"] is not None]
if not cand:
break
j = max(cand, key=lambda j: nodos[j]["mejor"][0])
_, k, u = nodos[j]["mejor"]
a = X[nodos[j]["idx"], k] < u
nodos[j].update(var=k, umbral=u, izq=hoja(nodos[j]["idx"][a]), der=hoja(nodos[j]["idx"][~a]))
hojas = [x for x in hojas if x != j] + [nodos[j]["izq"], nodos[j]["der"]]
def predecir(Z):
out, pila = np.empty(len(Z)), [(0, np.arange(len(Z)))]
while pila:
i, ix = pila.pop()
if "var" not in nodos[i]:
out[ix] = nodos[i]["w"]
continue
a = Z[ix, nodos[i]["var"]] < nodos[i]["umbral"]
pila += [(nodos[i]["izq"], ix[a]), (nodos[i]["der"], ix[~a])]
return out
return predecir
def datos(n, semilla):
r = np.random.default_rng(semilla)
X = r.normal(size=(n, 8))
y = np.sin(2 * X[:, 0]) + X[:, 1] * np.abs(X[:, 2]) + 0.5 * np.abs(X[:, 3]) + r.normal(0, 0.5, n)
return X, y
X, y = datos(10000, 1)
Xt, yt = datos(10000, 2)
T, eta, L = 10, 0.3, 15
t0 = time.perf_counter()
F, Ft = np.full(len(y), y.mean()), np.full(len(yt), y.mean())
for _ in range(T):
p = arbol_exacto(X, F - y, np.ones(len(y)), L, 20, 1.0)
F, Ft = F + eta * p(X), Ft + eta * p(Xt)
res = {"exacta": (time.perf_counter() - t0, np.mean((Ft - yt) ** 2))}
for mb in [255, 63, 15, 4]:
t0 = time.perf_counter()
m = MiniLGBM(Cuadratica(), n_arboles=T, eta=eta, max_bin=mb, num_leaves=L, min_data_in_leaf=20, lam=1.0).ajustar(X, y)
res[f"{mb} cubos"] = (time.perf_counter() - t0, np.mean((m.margen(Xt) - yt) ** 2))
for k, (t, e) in res.items():
print(f"{k:9s} error cuadrático de prueba {e:.4f} exacta / esta en tiempo: {res['exacta'][0] / t:4.1f}")
Xb20, _ = discretizar(datos(20000, 3)[0])
y20 = datos(20000, 3)[1]
for restar in (False, True):
a = ArbolHist(num_leaves=63, min_data_in_leaf=20, lam=1.0, restar=restar).ajustar(Xb20, y20.mean() - y20, np.ones(len(y20)), 256)
print("con la resta" if restar else "directo ", f"filas recorridas: {a.filas_recorridas / len(y20):.2f} n ({a.n_hojas} hojas, profundidad {a.profundidad})")With 255 bins test error () is even slightly lower than exact (). Discretization does not inherently improve the model: with ten greedy trees such a difference is within what changes when moving a midpoint threshold to a quantile boundary. The cell shows negligible accuracy loss with 255 and 63 bins, noticeable loss at 15 and severe loss at 4 when the model cannot follow . Time falls severalfold: both algorithms are vectorized, but exact sorts every feature in every leaf () while histogram only sums () and scans at most 255 cells. Exact ratio depends on machine and load; the robust point is that it is measured in multiples, not percentages. The last part measures the subtraction theorem on a 63-leaf tree: subtraction scans rows versus , less than half.
Leaf-wise versus level-wise
The peak-and-step figure’s model, now with boosting and two sample sizes, compares both policies with the same leaf budget.
import numpy as np
def pico(n, semilla):
r = np.random.default_rng(semilla)
X = r.uniform(size=(n, 4))
f = 1.6 * np.exp(-((X[:, 0] - 0.72) ** 2 + (X[:, 1] - 0.68) ** 2) / (2 * 0.09**2)) + 0.6 * (X[:, 0] < 0.3) + 0.5 * X[:, 2]
return X, f + r.normal(0, 0.35, n)
Xv, yv = pico(4000, 99)
print("suelo del ruido: sigma^2 = 0.1225")
for n, configs in [(400, [("niveles", 64, 6, 20), ("hojas", 64, -1, 20), ("hojas", 64, -1, 1), ("hojas", 64, 6, 20)]),
(4000, [("niveles", 8, 3, 20), ("hojas", 8, -1, 20), ("niveles", 64, 6, 20), ("hojas", 64, -1, 20)])]:
X, y = pico(n, 3)
for pol, L, D, mdl in configs:
m = MiniLGBM(Cuadratica(), n_arboles=30, eta=0.15, num_leaves=L, max_depth=D, min_data_in_leaf=mdl, politica=pol).ajustar(X, y)
prof = max(a.profundidad for a in m.arboles)
print(f"n = {n:4d} {pol:7s} num_leaves = {L:2d} max_depth = {D:2d} min_data = {mdl:2d} "
f"entrenamiento {np.mean((m.margen(X) - y) ** 2):.4f} validación {np.mean((m.margen(Xv) - yv) ** 2):.4f} profundidad máx. {prof}")With and 8 leaves, leaf-wise clearly wins ( validation versus ): it spends splits on the peak where error lies, while level-wise distributes three full levels over the square. With 64 leaves and no depth limit, leaf-wise branches reach 26 levels and validation is no longer better than the depth-6 level-wise tree ( versus ). With , removing min_data_in_leaf leaves single-row leaves: training error falls to and validation rises to , worst of all. The last line confirms the section result: with num_leaves and max_depth , leaf-wise exactly reproduces level-wise, digit by digit.
GOSS: bias and variance of sums
Now the GOSS theorem with the figure’s model but : mean and standard deviation of across 3000 batches versus exact value and variance formula, for GOSS and equal-size uniform sampling.
import numpy as np
r = np.random.default_rng(0)
n = 10000
x = r.uniform(size=n)
y = (r.random(n) < 1 / (1 + np.exp(-(10 * (x - 0.5) + 2.5 * (x > 0.7))))).astype(float)
izq = x <= 0.7
def var_mas(v, m):
"""Varianza del estimador de Horvitz-Thompson del total de v con una muestra aleatoria simple de m elementos."""
N = len(v)
return N**2 * (1 - m / N) * v.var(ddof=1) / m
for gam in (0.0, 1.0):
g = 1 / (1 + np.exp(-gam * 10 * (x - 0.5))) - y
v = g * izq # aportación de cada fila a G_L
orden = np.argsort(-np.abs(g), kind="stable")
for a, b in [(0.2, 0.1), (0.05, 0.05)]:
A, resto = orden[: int(a * n)], orden[int(a * n):]
mb, mu = int(b * n), int((a + b) * n)
eg = np.array([v[A].sum() + (1 - a) / b * v[r.choice(resto, mb, replace=False)].sum() for _ in range(3000)])
eu = np.array([n / mu * v[r.choice(n, mu, replace=False)].sum() for _ in range(3000)])
umbral = b / ((1 - a) * (a + b))
print(f"gamma = {gam:.0f}, a = {a}, b = {b}: G_L = {v.sum():7.2f}")
print(f" GOSS media {eg.mean():7.2f} desv. {eg.std():6.2f} (fórmula {np.sqrt(var_mas(v[resto], mb)):6.2f})")
print(f" uniforme media {eu.mean():7.2f} desv. {eu.std():6.2f} (fórmula {np.sqrt(var_mas(v, mu)):6.2f})")
print(f" S_r^2 / S^2 = {v[resto].var(ddof=1) / v.var(ddof=1):.3f} frente al umbral {umbral:.3f}")Both estimator means match within Monte Carlo error (one standard deviation divided by with 3000 batches), and measured deviations match the formula. The theorem’s criterion predicts the winner in all four cases. With all gradients equal , removing the largest does not reduce variance ( near 1) and GOSS clearly loses. With , and , removing the top 20% leaves only 16% of variance, far below threshold 0.417, and GOSS wins. With set is too small and large gradients remain: the threshold is less demanding but rises more and GOSS loses again.
Greedy EFB
A dataset with three one-hot categoricals (40, 25 and 10 levels) and 20 sparse numeric features (nonzero in 3% of rows, with 15 bins): algorithm 3 bundles, 4 merges with offsets, and we check that without conflicts each original feature’s histogram is exactly recovered from its bundle.
import numpy as np
r = np.random.default_rng(0)
n = 5000
cols = []
for K in [40, 25, 10]: # tres categóricas en one-hot
v = r.integers(0, K, n)
cols += [(v == j).astype(np.uint8) for j in range(K)]
for _ in range(20): # 20 numéricas dispersas: cubo 0 = «vale cero»
b = np.zeros(n, np.uint8)
nz = r.random(n) < 0.03
b[nz] = r.integers(1, 16, nz.sum())
cols.append(b)
Xb = np.column_stack(cols)
NZ = Xb > 0
nbin = Xb.max(0).astype(int) + 1
d = Xb.shape[1]
conf = NZ.T.astype(np.int64) @ NZ.astype(np.int64) # conflictos entre cada par de variables
np.fill_diagonal(conf, 0)
grado = (conf > 0).sum(1)
def agrupar(K, orden):
"""Algoritmo 3: cada variable al primer grupo cuyos conflictos acumulados no pasen de K."""
grupos, choques = [], []
for f in orden:
for j, gr in enumerate(grupos):
c = int((NZ[:, f] & NZ[:, gr].any(1)).sum())
if c + choques[j] <= K:
gr.append(f)
choques[j] += c
break
else:
grupos.append([f])
choques.append(0)
return grupos, choques
def fusionar(grupo):
"""Algoritmo 4: desplaza los cubos no nulos de cada variable; en un conflicto gana la última."""
nuevo, despl = np.zeros(n, np.int64), [0]
for f in grupo:
nz = Xb[:, f] > 0
nuevo[nz] = Xb[nz, f] + despl[-1]
despl.append(despl[-1] + nbin[f] - 1)
return nuevo, despl
orden = np.lexsort((-NZ.sum(0), -grado)) # por grado y, a igualdad, por no nulos
for K in [0, 5, 25]:
grupos, choques = agrupar(K, orden)
print(f"K = {K:2d}: {d} variables en {len(grupos)} grupos; filas con conflicto: {sum(choques)}")
g = r.normal(size=n)
grupos, _ = agrupar(0, orden)
error = 0.0
for gr in grupos:
nuevo, despl = fusionar(gr)
Hg = np.bincount(nuevo, g, despl[-1] + 1)
for j, f in enumerate(gr):
trozo = Hg[despl[j] + 1: despl[j + 1] + 1]
recuperado = np.r_[g.sum() - trozo.sum(), trozo] # el cubo 0 es lo que falta hasta el total
error = max(error, np.abs(recuperado - np.bincount(Xb[:, f], g, nbin[f])).max())
print("K = 0: máx |histograma recuperado - directo|:", error)
tipo = ["cat40"] * 40 + ["cat25"] * 25 + ["cat10"] * 10 + ["num"] * 20
composicion = lambda gr: {t: sum(tipo[f] == t for f in gr) for t in ["cat40", "cat25", "cat10", "num"] if any(tipo[f] == t for f in gr)}
for gr in [x for x in grupos if len(x) > 3]:
print(f" grupo de {len(gr):2d}:", composicion(gr))
print(" los otros", sum(len(x) <= 3 for x in grupos), "grupos:", [composicion(x) for x in grupos if len(x) <= 3])With no conflicts tolerated, 95 columns become 21, and each histogram built on a merged column contains all its features’ histograms without error except rounding: each bin 0 comes from subtracting from the already-known node total. The small categorical’s 10 indicators form a bundle, as do 23 of 25 and 29 of 40 in the other two; the 13 remaining indicators pair with sparse numeric features they never overlap. Numeric features, which collide in a few rows, remain alone, in pairs or with those indicators. Allowing 25 conflicts per bundle lowers the count to 8 columns at the cost of 118 rows losing a feature.
Leakage-free target statistics
The four encodings from the CatBoost section, on data with a 300-level categorical with no effect and another 30-level categorical with real effect (logit offsets with deviation 0.8), training minimal LightGBM on each.
import numpy as np
def ts_ingenua(c, y, prior, a):
s, m = np.bincount(c, y), np.bincount(c).astype(float)
return (s[c] + a * prior) / (m[c] + a)
def ts_loo(c, y, prior, a):
s, m = np.bincount(c, y), np.bincount(c).astype(float)
return (s[c] - y + a * prior) / (m[c] - 1 + a)
def ts_pliegues(c, y, prior, a, k=5, semilla=0):
pl = np.random.default_rng(semilla).permutation(len(y)) % k
out = np.empty(len(y))
for f in range(k):
dentro = pl == f
s = np.bincount(c[~dentro], y[~dentro], c.max() + 1)
m = np.bincount(c[~dentro], minlength=c.max() + 1)
out[dentro] = (s[c[dentro]] + a * prior) / (m[c[dentro]] + a)
return out
def ts_ordenada(c, y, prior, a, perm):
s, m, out = np.zeros(c.max() + 1), np.zeros(c.max() + 1), np.empty(len(y))
for i in perm: # cada fila, con la historia de su categoría
out[i] = (s[c[i]] + a * prior) / (m[c[i]] + a)
s[c[i]] += y[i]
m[c[i]] += 1
return out
def ts_prueba(c_tr, y, c_te, prior, a):
K = max(c_tr.max(), c_te.max()) + 1
s, m = np.bincount(c_tr, y, K), np.bincount(c_tr, minlength=K).astype(float)
return (s[c_te] + a * prior) / (m[c_te] + a)
efecto = np.random.default_rng(42).normal(0, 0.8, 30)
def datos_cat(n, semilla):
r = np.random.default_rng(semilla)
x = r.normal(size=n)
ruido = r.integers(0, 300, n) # 300 niveles sin ningún efecto
util = r.integers(0, 30, n) # 30 niveles con efecto real
z = 1.2 * x - 0.3 + efecto[util]
return x, ruido, util, z, (r.random(n) < 1 / (1 + np.exp(-z))).astype(float)
x, ru, ut, _, y = datos_cat(3000, 1)
xt, rut, utt, zt, yt = datos_cat(10000, 2)
p0, a = y.mean(), 1.0
L = Logistica()
perm = np.random.default_rng(7).permutation(len(y))
print(f"pérdida de Bayes en prueba: {L.valor(yt, zt):.4f}")
for nombre, cod in [("ingenua", lambda c: ts_ingenua(c, y, p0, a)), ("leave-one-out", lambda c: ts_loo(c, y, p0, a)),
("5 pliegues", lambda c: ts_pliegues(c, y, p0, a)), ("ordenada", lambda c: ts_ordenada(c, y, p0, a, perm))]:
Xtr = np.column_stack([x, cod(ru), cod(ut)])
Xte = np.column_stack([xt, ts_prueba(ru, y, rut, p0, a), ts_prueba(ut, y, utt, p0, a)])
m = MiniLGBM(L, n_arboles=60, eta=0.15, num_leaves=15, min_data_in_leaf=20, lam=1.0).ajustar(Xtr, y)
imp = m.importancia(3)
print(f"{nombre:13s} pérdida: entrenamiento {L.valor(y, m.margen(Xtr)):.4f} prueba {L.valor(yt, m.margen(Xte)):.4f}"
f" importancia: x {imp[0]:.2f} ruido {imp[1]:.2f} útil {imp[2]:.2f}")Naive TS gives the noise categorical 26% of gain and opens a large training–test gap ( versus ). Leave-one-out is worse, for the paper’s reason: the useful categorical has about 100 rows per level, and within each level leave-one-out perfectly separates labels, so the model gives it 84% of gain, training loss plummets to and test loss shoots to . The paper finds the same with real data: leave-one-out also fails with frequent categories, and in Adult, where all are frequent, it is worst (table 4). With five folds and ordered, noise importance falls (0.12 and 0.09), is most important again and test loss is closest to Bayes ( and versus ).
Prediction shift, measured
Finally theorem 1 by Monte Carlo, with and : classical model (both stumps with same sample), a second independent sample for the second stump, and ordered residuals.
import numpy as np
c1, c2 = 2.0, 1.0
def tocon(xa, ya, valido):
"""Media de ya por valor de xa (un tocón por réplica), solo con las filas válidas."""
num = np.stack([((xa == s) & valido) * ya for s in (0, 1)], 1).sum(2)
den = np.stack([(xa == s) & valido for s in (0, 1)], 1).sum(2)
return num / np.maximum(den, 1), (den > 0).all(1)
def experimento(n, R, semilla):
r = np.random.default_rng(semilla)
rep = np.arange(R)
muestra = lambda: (r.integers(0, 2, (R, n)), r.integers(0, 2, (R, n)))
x1, x2 = muestra()
y = c1 * x1 + c2 * x2
todos = np.ones((R, n), bool)
h1, ok1 = tocon(x1, y, todos) # primer tocón con toda la muestra
res = y - h1[rep[:, None], x1] # residuos clásicos, en las mismas filas
h2, ok2 = tocon(x2, res, todos)
z1, z2 = muestra() # segunda muestra independiente
h2i, ok3 = tocon(z2, c1 * z1 + c2 * z2 - h1[rep[:, None], z1], todos)
cnt, suma = np.zeros((R, 2)), np.zeros((R, 2)) # residuos ordenados: la fila k solo usa las anteriores
res_o, val_o = np.zeros((R, n)), np.zeros((R, n), bool)
for k in range(n):
s = x1[:, k]
c = cnt[rep, s]
val_o[:, k] = c > 0
res_o[:, k] = y[:, k] - suma[rep, s] / np.maximum(c, 1)
cnt[rep, s] += 1
suma[rep, s] += y[:, k]
h2o, ok4 = tocon(x2, res_o, val_o)
F01 = lambda segundo, ok: (h1[:, 0] + segundo[:, 1])[ok1 & ok].mean() - c2 # F(0, 1) - f*(0, 1)
return {"residuo clásico": res[(x2 == 1) & ok1[:, None]].mean(), # cada media, con las réplicas
"residuo ordenado": res_o[(x2 == 1) & val_o].mean(), # en las que está definida
"sesgo clásico": F01(h2, ok2), "sesgo independiente": F01(h2i, ok3), "sesgo ordenado": F01(h2o, ok4)}
print("en un ejemplo nuevo con x2 = 1, el residuo medio es c2/2 = 0.5")
for n in [5, 10, 50]:
e = experimento(n, 60000, n)
print(f"n = {n:2d}: residuo medio con x2 = 1: clásico {e['residuo clásico']:.4f} ordenado {e['residuo ordenado']:.4f}")
print(f" sesgo de F en x = (0, 1): clásico {e['sesgo clásico']:+.4f} (teorema {-c2 * 0.5 / (n - 1):+.4f})"
f" independiente {e['sesgo independiente']:+.4f} ordenado {e['sesgo ordenado']:+.4f}")The paper’s whole chain appears. Classical residuals for rows with are below 0.5 (, and for , 10 and 50): the first link, training gradient shifted relative to a new example. The second stump fits them and bias matches theorem at all three sizes; with a second independent sample it is zero within Monte Carlo error. Ordered residuals have exactly the mean of a new example, as ordered boosting promises. But bias with them does not vanish: its sign reverses and for is similar in size to classical bias. This measures the previous section’s nuance: the second stump fits residuals of supporting models that are not the final model’s first stump.
LightGBM and CatBoost locally
The next two cells run on your machine with real libraries (LightGBM 4.7 and CatBoost 1.2 in the course environment) on Amazon Employee Access, a CatBoost paper dataset: 32 769 resource access requests with 9 categoricals (resource, manager, department, role…) and a highly imbalanced binary label. The first cell downloads it from OpenML, prints LightGBM defaults read from the model itself and compares four ways to provide categoricals with the same training, validation (for early stopping) and test split.
import time
import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.metrics import log_loss, roc_auc_score
print("lightgbm", lgb.__version__)
datos = fetch_openml(data_id=4135, as_frame=True, parser="liac-arff") # Amazon Employee Access
X = datos.data.apply(lambda c: c.astype(str))
y = (datos.target.astype(str) == "1").astype(int).to_numpy()
print("forma", X.shape, " fracción de y = 1:", round(y.mean(), 4))
print("niveles por variable:", X.nunique().to_dict())
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
Xfit, Xval, yfit, yval = train_test_split(Xtr, ytr, test_size=0.2, random_state=1, stratify=ytr)
print("filas: entrenamiento", len(Xfit), " validación", len(Xval), " prueba", len(Xte))
print("filas de prueba con un RESOURCE que no aparece en entrenamiento:", round((~Xte["RESOURCE"].isin(set(Xfit["RESOURCE"]))).mean(), 3))
# valores por defecto, leídos de un modelo entrenado sin fijar nada
b0 = lgb.train({"objective": "binary", "verbose": -1}, lgb.Dataset(np.random.rand(50, 2), np.arange(50) % 2), 1)
seccion = b0.model_to_string().split("parameters:")[1].split("end of parameters")[0]
par = dict(l[1:-1].split(": ", 1) for l in seccion.strip().splitlines())
print("por defecto:", {k: par[k] for k in ["num_leaves", "max_depth", "min_data_in_leaf", "max_bin", "learning_rate", "max_cat_to_onehot",
"cat_smooth", "cat_l2", "min_data_per_group", "max_cat_threshold", "top_rate", "other_rate"]})
def ts_ingenua(fit, yv, otros, a=1.0):
p, out = yv.mean(), [pd.DataFrame(index=D.index) for D in [fit] + otros]
for c in fit:
g = pd.DataFrame({"c": fit[c].to_numpy(), "y": yv}).groupby("c")["y"].agg(["sum", "count"])
enc = (g["sum"] + a * p) / (g["count"] + a)
for D, o in zip([fit] + otros, out):
o[c] = D[c].map(enc).astype(float).fillna(p).to_numpy()
return out
def ts_ordenada(fit, yv, otros, a=1.0, semilla=0):
p, perm = yv.mean(), np.random.default_rng(semilla).permutation(len(yv))
out = ts_ingenua(fit, yv, otros, a) # validación y prueba: todas las filas de entrenamiento
for c in fit:
_, inv = np.unique(fit[c].to_numpy(), return_inverse=True)
s, m, col = np.zeros(inv.max() + 1), np.zeros(inv.max() + 1), np.empty(len(yv))
for i in perm:
col[i] = (s[inv[i]] + a * p) / (m[inv[i]] + a)
s[inv[i]] += yv[i]
m[inv[i]] += 1
out[0][c] = col
return out
def entrenar(Ftr, Fva, Fte, cat):
P = {"objective": "binary", "learning_rate": 0.05, "num_leaves": 31, "verbose": -1, "seed": 0}
dtr = lgb.Dataset(Ftr, yfit, categorical_feature=cat, free_raw_data=False)
dva = lgb.Dataset(Fva, yval, reference=dtr, categorical_feature=cat)
bst = lgb.train(P, dtr, 3000, valid_sets=[dva], callbacks=[lgb.early_stopping(100, verbose=False)])
pte, ptr = bst.predict(Fte, num_iteration=bst.best_iteration), bst.predict(Ftr, num_iteration=bst.best_iteration)
imp = bst.feature_importance("gain")
return (f"prueba {log_loss(yte, pte):.4f} AUC {roc_auc_score(yte, pte):.4f} entrenamiento {log_loss(yfit, ptr):.4f}"
f" árboles {bst.best_iteration:4d} más importante: {Ftr.columns[imp.argmax()]} ({imp.max() / imp.sum():.2f})")
niveles = {c: pd.Index(sorted(Xfit[c].unique())) for c in X}
codigos = lambda D: pd.DataFrame({c: niveles[c].get_indexer(D[c]) for c in D}, index=D.index) # -1: nivel nuevo
Cfit, Cval, Cte = codigos(Xfit), codigos(Xval), codigos(Xte)
print("enteros como ordinales ", entrenar(Cfit.replace(-1, np.nan), Cval.replace(-1, np.nan), Cte.replace(-1, np.nan), cat=[]))
print("categóricas nativas ", entrenar(Cfit, Cval, Cte, cat=list(X.columns)))
print("TS ingenua ", entrenar(*ts_ingenua(Xfit, yfit, [Xval, Xte]), cat=[]))
print("TS ordenada ", entrenar(*ts_ordenada(Xfit, yfit, [Xval, Xte]), cat=[]))npm run lab and open the connection link.The second cell moves to CatBoost: it prints defaults chosen for this dataset, compares Ordered and Plain on full training and 10% (several seeds because differences are small), and measures CPU versus GPU in CatBoost and LightGBM. It then compares GOSS with uniform sampling in the library on synthetic data from the GOSS section’s two regimes.
import time, tempfile
import numpy as np
import lightgbm as lgb
import catboost as cb
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.metrics import log_loss
print("catboost", cb.__version__)
datos = fetch_openml(data_id=4135, as_frame=True, parser="liac-arff")
X = datos.data.apply(lambda c: c.astype(str))
y = (datos.target.astype(str) == "1").astype(int).to_numpy()
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
cats, carpeta = list(X.columns), tempfile.mkdtemp()
def catboost(Xa, ya, modo, semilla, task="CPU", it=3000, lr=0.05, parada=True):
Xf, Xv, yf, yv = train_test_split(Xa, ya, test_size=0.2, random_state=semilla, stratify=ya)
P = dict(iterations=it, learning_rate=lr, depth=6, loss_function="Logloss", boosting_type=modo, random_seed=semilla,
verbose=0, task_type=task, train_dir=carpeta, allow_writing_files=False)
if parada:
P.update(od_type="Iter", od_wait=100, use_best_model=True)
m = cb.CatBoostClassifier(**P)
t0 = time.perf_counter()
m.fit(Xf, yf, cat_features=cats, eval_set=(Xv, yv))
return log_loss(yte, m.predict_proba(Xte)[:, 1]), m.get_best_iteration(), time.perf_counter() - t0
m0 = cb.CatBoostClassifier(iterations=5, verbose=0, train_dir=carpeta, allow_writing_files=False).fit(Xtr, ytr, cat_features=cats)
ap = m0.get_all_params()
print("por defecto:", {k: ap.get(k) for k in ["depth", "learning_rate", "border_count", "boosting_type", "grow_policy",
"l2_leaf_reg", "one_hot_max_size", "max_ctr_complexity", "random_strength"]})
for frac, semillas in [(1.0, 3), (0.1, 5)]:
for modo in ["Plain", "Ordered"]:
res = []
for s in range(semillas):
idx = np.random.default_rng(100 + s).choice(len(ytr), int(frac * len(ytr)), replace=False)
res.append(catboost(Xtr.iloc[idx], ytr[idx], modo, s))
res = np.array(res)
print(f"fracción {frac:.1f} {modo:7s} pérdida de prueba {res[:, 0].mean():.4f} ± {res[:, 0].std():.4f}"
f" árboles {res[:, 1].mean():5.0f} segundos {res[:, 2].mean():5.1f}")
for task in ["CPU", "GPU"]:
try:
ll, _, t = catboost(Xtr, ytr, "Plain", 0, task=task, it=500, lr=0.1, parada=False)
print(f"CatBoost {task}: 500 árboles en {t:.1f} s, pérdida de prueba {ll:.4f}")
except Exception as e:
print(f"CatBoost {task} no disponible: {str(e)[:120]}")
Z = np.random.default_rng(0).normal(size=(200000, 50))
yz = (Z[:, 0] + Z[:, 1] * Z[:, 2] + np.random.default_rng(1).normal(size=200000) > 0).astype(int)
for dev in ["cpu", "gpu", "cuda"]:
try:
t0 = time.perf_counter()
lgb.train({"objective": "binary", "device_type": dev, "verbose": -1, "num_leaves": 63}, lgb.Dataset(Z, yz), 200)
print(f"LightGBM {dev}: 200 árboles en {time.perf_counter() - t0:.1f} s")
except Exception as e:
print(f"LightGBM {dev} no disponible: {str(e)[:120]}")
def regimen(escala, n, semilla):
r = np.random.default_rng(semilla)
Xs = r.normal(size=(n, 10))
z = escala * (1.5 * Xs[:, 0] - Xs[:, 1] + np.sin(2 * Xs[:, 2]) + Xs[:, 3] * np.abs(Xs[:, 4]))
return Xs, (r.random(n) < 1 / (1 + np.exp(-z))).astype(int)
for escala in (1.0, 3.0):
Xs, ys = regimen(escala, 100000, 1)
Xp, yp = regimen(escala, 100000, 2)
base = {"objective": "binary", "learning_rate": 0.1, "num_leaves": 31, "verbose": -1}
for nombre, extra in [("todas las filas", {}), ("GOSS 0.2 + 0.1", {"data_sample_strategy": "goss"}),
("uniforme 30 %", {"bagging_fraction": 0.3, "bagging_freq": 1})]:
v, t = [], []
for s in range(3):
t0 = time.perf_counter()
bst = lgb.train({**base, **extra, "seed": s}, lgb.Dataset(Xs, ys), 300)
t.append(time.perf_counter() - t0)
v.append(log_loss(yp, bst.predict(Xp)))
print(f"escala {escala:.0f} {nombre:16s} pérdida de prueba {np.mean(v):.4f} ± {np.std(v):.4f} segundos {np.mean(t):.1f}")npm run lab and open the connection link.These are the course verification run’s results on a shared machine; times are only order-of-magnitude.
The dataset. 94.2% of requests are approved, so rejection is the rare class. Categoricals range from 67 levels (ROLE_FAMILY) to 7518 (RESOURCE) and 4243 (MGR_ID), and 15.9% of test rows have a resource absent from training: any TS for them equals the prior. LightGBM’s printed defaults are those cited in the lesson: 31 leaves, unlimited depth, 20 rows per leaf, 255 bins, max_cat_to_onehot , cat_smooth , top_rate and other_rate .
Four ways to give categoricals to LightGBM. Same split and early stopping:
| Encoding | Test loss | AUC | Training loss | Trees |
|---|---|---|---|---|
| integers as ordinal | 0.1695 | 0.8265 | 0.1120 | 250 |
| native categoricals | 0.1557 | 0.8527 | 0.0891 | 81 |
| naive TS | 0.1867 | 0.8012 | 0.0829 | 17 |
| ordered TS | 0.1569 | 0.8646 | 0.1284 | 133 |
Naive TS has lowest training loss and worst test loss, and early stopping cuts it at 17 trees: validation quickly detects learned patterns do not generalize, and manager (MGR_ID) takes 56% of gain. Ordered TS reaches and best AUC: naive has 19% more loss. The CatBoost paper measures a larger 40% difference on Amazon (table 4, CatBoost in Ordered rather than LightGBM). Native LightGBM categoricals match ordered TS in loss () and trail in AUC. Ordinal identifiers need 250 trees to reach : thresholding an arbitrary order works poorly and slowly.
CatBoost. In this version, dataset and CPU, defaults are depth 6, 254 boundaries per feature, boosting_type="Plain", symmetric trees (SymmetricTree), l2_leaf_reg and one_hot_max_size . Printed rate 0.5 is not universal: CatBoost selects it based on iteration count, and that test model had 5. On full training test loss is in Plain and in Ordered (three seeds): on Amazon Plain is slightly better, as in paper table 3 (). With 10% of data, versus (five seeds): the difference is much smaller than variation across seeds, so this experiment cannot claim Ordered helps here. The gap to LightGBM is clear: versus or , of the same order as table 2’s 17% CatBoost advantage on Amazon, though using a different protocol.
GPU. CatBoost on GPU builds 500 trees three to four times faster than CPU (exact ratio varied between runs on this shared machine), with different test loss ( versus ), because GPU implementation does not exactly reproduce CPU. The pip LightGBM wheel has no GPU: both device_type="gpu" and "cuda" say the library must be recompiled with -DUSE_GPU=1 or -DUSE_CUDA=1.
GOSS in the library. With 100 000 rows, 300 trees and the same per-tree row fraction (30%), GOSS (, ) versus uniform subsampling:
| Regime | All rows | GOSS | Uniform 30% |
|---|---|---|---|
| high noise (scale 1) | 0.4525 | 0.4628 | 0.4581 |
| low noise (scale 3) | 0.2035 | 0.2043 | 0.2083 |
This is the variance theorem with the real implementation: when gradients are distributed (high noise), GOSS is worse than random row removal; when concentrated, GOSS stays near all-row loss and uniform does not. Deviations between seeds are one or a few ten-thousandths, so both differences are real.
Common mistakes
Exercises
max_depth = 7 to have the same maximum capacity as a level-wise tree of that depth. Which num_leaves achieves it, and why does documentation recommend less?Step 1 of 4. How do you rewrite the random part of ?
build_histogram(bins, g, h, n_bins), receiving a feature's bins (integers 0 to n_bins - 1) and gradients and Hessians of node rows, returning two arrays of length n_bins with sums of g and h per bin; and subtract_histogram(parent, child), receiving two (G, H) pairs and returning the sibling pair. Do not use Python loops over rows. Then children_histograms(bins, g, h, n_bins, left_mask, parent) must return (izquierdo, derecho) (left, right) histograms by directly building only the child with fewer rows and obtaining the other by subtraction. Tests compare direct construction and check only the smaller child is built.import numpy as np
def build_histogram(bins, g, h, n_bins):
# tu código: suma de g y de h por cubo
return np.zeros(n_bins), np.zeros(n_bins)
def subtract_histogram(parent, child):
# tu código
return parent
def children_histograms(bins, g, h, n_bins, left_mask, parent):
"""Devuelve ((G_L, H_L), (G_R, H_R)) construyendo solo el hijo pequeño."""
# tu código
return parent, parentordered_target_statistics(categories, y, prior, a, perm): categories is an integer array (each row's level), y labels, prior and a prior and weight, and perm a row permutation (history order: perm[0] is the first row). Row i's encoding must be , where sum and count cover only same-category rows preceding i in perm. Return an array of each row's encoding in original order. Tests check known cases, that a row's encoding does not depend on its own label, and linear complexity (without rescanning each row's history from scratch).import numpy as np
def ordered_target_statistics(categories, y, prior, a, perm):
categories, y = np.asarray(categories), np.asarray(y, float)
out = np.empty(len(y))
# tu código: recorre perm acumulando, por categoría, la suma de y y el recuento
return outSummary
- Histograms. Discretizing once into up to 255 bins (one byte per value) turns split search into bin sums: to build and to scan. Building only the smaller child and subtracting scans at most rows per level and each row at most times.
- Leaf-wise. Always splitting the highest-gain leaf reduces loss more with the same leaves at the cost of deep branches. With
max_depth,num_leavesmust not exceed and should stay below; withnum_leavesand all splits valid, it matches level-wise. - GOSS. With weight , gradient and Hessian sums are unbiased Horvitz–Thompson estimates; nonlinear gain is optimistic. GOSS has lower variance than uniform sampling if and only if : when gradients are concentrated.
- EFB. Optimal bundling is NP-hard (equivalent to conflict-graph coloring); degree-greedy with tolerated conflicts reduces cost from to on sparse data and does not help dense data.
- TS leakage. Naive TS includes the row’s label and mistakes noise for signal; leave-one-out also leaks via shift . Cross-fitting and ordered TS do not see the row’s label.
- Prediction shift. Reusing data to calculate gradients biases the model by in the theorem’s example. CatBoost calculates gradients choosing structure with supporting models that have not seen the row; final leaf values use the standard procedure. The
Orderedgain is small and concentrated on small datasets. - Symmetric trees. One split per level: the leaf is the binary number of independent comparisons, enabling fast vectorized inference and a more regularized tree family.