Module contents
Lesson 19 of 24Advanced 120 min

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 gig_i and hih_i, each leaf receives the optimal weight −G/(H+λ)-G/(H + \lambda), 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 O(#datos×#variables)\bigO(\#\text{datos} \times \#\text{variables}) and searching them for a split costs O(#cubos×#variables)\bigO(\#\text{cubos} \times \#\text{variables}); 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 tt 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 BB 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 20 000×820\,000 \times 8 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 0.41690.4169 with exact search and 0.41210.4121 with 255 bins, degrading only with very few bins (0.45150.4515 with 15 and 0.82080.8208 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 II splits into IL⊔IRI_L \sqcup I_R, each parent cell is the sum of the children’s, Gkb(I)=Gkb(IL)+Gkb(IR)G_{kb}(I) = G_{kb}(I_L) + G_{kb}(I_R), and likewise for HH and NN, 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 O(B d)\bigO(B\, d) 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 mm rows builds a histogram of min⁡(mL,mR)≤m/2\min(m_L, m_R) \le m/2 rows. Nodes split on the same level have disjoint row sets, so their mm sum to at most nn and what is built to at most n/2n/2. Summing the root and DD split levels yields n+Dn/2n + Dn/2. Direct construction scans mL+mR=mm_L + m_R = m rows per split, at most nn 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 mm to at most m/2m/2. Starting at nn and never below one row, this can happen only ⌊log⁡2n⌋\lfloor \log_2 n \rfloor 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 20 00020\,000 rows scans 7.58 n7.58\,n rows building both children and 3.07 n3.07\,n with subtraction, below bound n(1+9/2)=5.5 nn(1 + 9/2) = 5.5\,n. Subtraction also has a numerical cost: in floating point G(I)−G(IS)G(I) - G(I_S) is not exactly the direct sum of ILI_L, but the difference is on the order of rounding (2⋅10−142 \cdot 10^{-14} in the lab), and integer counts NkbN_{kb} are exact.

InteractiveThe subtraction trick
Node samples: xx bins and split on zz
z = τ
Subtracting bin 7.
Histogramas de gradientes por cubo de x
parent (already computed)left child, z < 0.30 (9)right child, z ≥ 0.30 (31)01234567
  • left child
  • right child
  • split z=τz = \tau and bin being subtracted
How children are obtained
Histogram displayed
0.30
8
operation 17 of 17
Operations performed17 of 17
Direct: one addition per node sample40
Subtraction: smaller-child samples + bins9 + 8 = 17
Maximum subtraction error versus direct2.2e−16
Only the 9 samples in the smaller left child are scanned. The other child follows from Hlarge=Hparent−HsmallH_{\text{large}} = H_{\text{parent}} - H_{\text{small}} using 8 subtractions, one per bin, without touching its 31 samples.
A node with 40 samples from an explicit model: independent x,z∼Unif⁡(0,1)x, z \sim \Unif(0, 1), y∼Bern⁡(σ(4(x−0.5)+2(z−0.5)))y \sim \Bern(\sigmoid(4(x - 0.5) + 2(z - 0.5))) and a current model with margin F=2(x−0.5)F = 2(x - 0.5), producing g=σ(F)−yg = \sigmoid(F) - y and h=σ(F)(1−σ(F))h = \sigmoid(F)(1 - \sigmoid(F)). Feature xx is discretized into BB quantile bins (vertical lines) and the node is split at z<τz < \tau (dashed line). At right, histograms of parent and both children. Direct mode scans all 40 samples; subtraction mode only the smaller child's, obtaining the larger bin by bin from the parent. Play both modes and compare the counter; then take τ\tau to 0.5 and 0.1.

Notice two things. With τ=0.3\tau = 0.3, the smaller child has 9 of 40 samples and subtraction takes 17 operations (9 additions and 8 bin subtractions) instead of 40. With τ=0.5\tau = 0.5, 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 BB 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 LL leaves has depth ⌈log⁡2L⌉\lceil \log_2 L \rceil, and a leaf-wise tree can reach depth L−1L - 1 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-DD tree has at most 2D2^D leaves, so with max_depth =D= D fixed, num_leaves above 2D2^D adds nothing. And if, with max_depth =D= D, num_leaves is =2D= 2^D and all nodes in the first DD 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 DD levels gives the same result in any order. You will verify this in the lab: with 64 leaves and max_depth =6= 6, both policies give identical errors. LightGBM’s tuning guide gives max_depth =7= 7: 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 =−1= -1 (unlimited) and min_data_in_leaf =20= 20, as the local lab shows.

InteractiveLeaf-wise versus level-wise
Level-wise (depth-wise)
profundidad 0
Leaf-wise
profundidad 0
  • peak and step of ff; each rectangle is a leaf, darker for larger values
Mean squared error versus number of leaves
  • validation, level-wise
  • validation, leaf-wise
  • training, level-wise
  • training, leaf-wise
  • noise σ²
1 leaves
200
5
Leaves1
Depth: level-wise / leaf-wise0 / 0
Training MSE: level-wise / leaf-wise0.241 / 0.241
Validation MSE: level-wise / leaf-wise0.236 / 0.236
Best validation: level-wise / leaf-wise0.168 (21 h.) / 0.153 (6 h.)
With 1 leaf, a complete level-wise tree has depth at most ⌈log⁡21⌉=0\lceil\log_2 1\rceil = 0; the leaf-wise tree reached 0. Noise sets the validation-error floor at σ2=0.1225\sigma^2 = 0.1225.
One least-squares regression tree (the first boosting round from the mean) fitted to explicit-model data: x∼Unif⁡([0,1]2)\vb{x} \sim \Unif([0, 1]^2) and y=f(x)+εy = f(\vb{x}) + \eps with ε∼N(0,0.352)\eps \sim \Normal(0, 0.35^2), where ff has a narrow peak of height 1.6 at (0.72,0.68)(0.72, 0.68) (dashed circle) and a 0.6 step at x1<0.3x_1 < 0.3 (dashed line). Both trees grow leaf by leaf with the same budget: level-wise splits nodes breadth-first and leaf-wise always takes the greatest error reduction. Below, training error (dashed) and validation error on 2,000 new points versus leaf count, with noise floor σ2=0.1225\sigma^2 = 0.1225. Play growth, lower min_data_in_leaf to 1 and try 100 and 800 samples.

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 (0.1640.164 versus 0.1970.197); its best validation arrives earlier, at 6 leaves (0.1530.153), while level-wise needs 21 to reach 0.1680.168. With 800 samples the advantage remains (0.1440.144 with 8 leaves versus 0.1620.162 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 0.0070.007 and validation rises to 0.2850.285, 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 ∣gi∣\abs{g_i} is already well fitted; one with large ∣gi∣\abs{g_i} 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 b×len(I)b \times \text{len}(I) rows from the remainder, as above, but section 3.2’s text says BB has size b×∣Ac∣b \times \abs{A^c}. Under the second reading the correct factor would be 1/b1/b, not (1−a)/b(1 - a)/b. Implementation follows the algorithm: in goss.hpp, small-row count is cnt * other_rate and multiplier (cnt - top_k) / other_k, i.e., (1−a)/b(1 - a)/b.

Proof

AA is determined by gradients, so ∑ALgi\sum_{A_L} g_i is not random. BB is a simple random sample of bnbn rows out of (1−a)n(1 - a)n in AcA^c, so each i∈Aci \in A^c enters BB with probability π=bn/((1−a)n)=b/(1−a)\pi = bn / ((1 - a)n) = b/(1 - a). Writing ∑BLgi=∑i∈ALcgi 1[i∈B]\sum_{B_L} g_i = \sum_{i \in A^c_L} g_i\, \ind[i \in B] and taking expectations gives E[1−ab∑BLgi]=1−ab π∑ALcgi=∑ALcgi\E\big[\tfrac{1 - a}{b}\sum_{B_L} g_i\big] = \tfrac{1 - a}{b}\, \pi \sum_{A^c_L} g_i = \sum_{A^c_L} g_i. Adding AA‘s part gives E[G^L]=∑ALgi+∑ALcgi=GL\E[\hat G_L] = \sum_{A_L} g_i + \sum_{A^c_L} g_i = G_L, likewise for HH. Factor (1−a)/b=1/π(1 - a)/b = 1/\pi is the weight of a Horvitz–Thompson estimator: each sampled row represents 1/π1/\pi rows in its stratum.

∎

Unbiased sums do not make gain unbiased. Gain is G^L2/(H^L+λ)+…\hat G_L^2/(\hat H_L + \lambda) + \dots, a nonlinear function, and by Jensen’s inequality E[G^L2]=GL2+Var⁡(G^L)>GL2\E[\hat G_L^2] = G_L^2 + \Var(\hat G_L) > G_L^2: 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 mm elements from a population of NN, the total estimator Nm∑muestravi\frac{N}{m}\sum_{\text{muestra}} v_i has variance N2(1−m/N)S2/mN^2 (1 - m/N) S^2 / m, where S2S^2 is population sample variance. In uniform sampling, N=nN = n and m=(a+b)nm = (a + b)n: n2(1−a−b)S2/((a+b)n)n^2(1 - a - b) S^2/((a + b)n). In GOSS, AA‘s part is fixed and BB‘s is that estimator with N=(1−a)nN = (1 - a)n and m=bnm = bn: (1−a)2n2(1−b/(1−a))Sr2/(bn)=(1−a)(1−a−b)nSr2/b(1 - a)^2 n^2 (1 - b/(1 - a)) S_r^2 / (bn) = (1 - a)(1 - a - b) n S_r^2 / b. The ratio is (1−a)(a+b)b⋅Sr2S2\frac{(1 - a)(a + b)}{b} \cdot \frac{S_r^2}{S^2}, less than 1 exactly under the stated condition.

∎

The threshold is intuitive. If a=0a = 0, GOSS is uniform sampling (Sr=SS_r = S and threshold 1). With a=0.2a = 0.2 and b=0.1b = 0.1, LightGBM defaults, GOSS wins if removing the 20% highest-gradient rows leaves variance under 41.7 %41.7\,\% of the total. This happens when gradients are concentrated: a few poorly fitted rows and a mostly solved majority. When all ∣gi∣\abs{g_i} are similar, as in the first classification round with p=0.5p = 0.5 for everyone, removing the top reduces nothing and GOSS loses because it samples the remainder at rate b/(1−a)b/(1 - a) below uniform’s a+ba + b. 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 AA; the formula above is exact for sums.

InteractiveGOSS: keep the informative rows
Gradients gig_i and what GOSS does with each sample (one batch)
x ≤ 0.70
Ganancia estimada en 500 tandas frente a la exacta (15 de 1000 estimaciones quedan a la derecha del gráfico)
exacta
  • retained: top ana n by ∣g∣|g| (weight 1)
  • sampled from remainder (weight (1−a)/b(1-a)/b, size ∝ weight)
  • discarded in this batch
  • GOSS histogram
  • uniform-sampling histogram
0.20
0.10
1.00
0.70
Weight of small-gradient samples (1−a)/b(1-a)/b8.00
Rows used per tree60 + 30 = 90 of 300 (30 %)
Exact gain (all rows)3.221
GOSS: mean ± deviation3.318 ± 1.712
Uniform: mean ± deviation3.536 ± 2.469
Exact GLG_L and GOSS mean2.26 / 2.35
The 60 retained rows account for 65 % of ∑∣gi∣\sum |g_i|: gradients are concentrated and GOSS reduces estimated-gain standard deviation to 69 % of uniform sampling with the same row count.
An explicit model with 300 samples: x∼Unif⁡(0,1)x \sim \Unif(0, 1) and y∼Bern⁡(σ(z∗(x)))y \sim \Bern(\sigmoid(z^*(x))) with z∗(x)=10(x−0.5)+2.5 1[x>0.7]z^*(x) = 10(x - 0.5) + 2.5\,\ind[x > 0.7]. The current model has margin F=γ⋅10(x−0.5)F = \gamma \cdot 10(x - 0.5): with γ=0\gamma = 0 it predicts 0.5 for all and with γ=1\gamma = 1 it has learned slope but not the step. Left, gi=σ(F)−yig_i = \sigmoid(F) - y_i versus xx: in magenta the anan largest-∣g∣\abs{g} rows, orange the bnbn sampled from the rest in one batch (size proportional to weight), gray discarded. Right, Newton gain of split x≤dx \le d (λ=1\lambda = 1) estimated over 500 batches by GOSS (magenta) and uniform sampling of the same row count (blue), against exact gain on all rows. Move γ\gamma to 0 and back to 1; lower aa to 0.05 with b=0.05b = 0.05.

In the initial state (γ=1\gamma = 1, a=0.2a = 0.2, b=0.1b = 0.1), large gradients are examples misclassified near boundary x=0.5x = 0.5, and the 60 retained rows sum to 65% of ∑∣gi∣\sum \abs{g_i}. The split signal, step x>0.7x > 0.7, 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 1.711.71 versus 2.472.47), and both means (3.323.32 and 3.543.54) lie right of exact gain 3.223.22: Jensen optimism, greater for the wider estimator. With γ=0\gamma = 0, all ∣gi∣\abs{g_i} are almost equal and the order reverses. The lab cell quantifies this with n=10 000n = 10\,000 and the theorem’s formula: with γ=1\gamma = 1, standard deviation of G^L\hat G_L is 27.627.6 for GOSS and 44.744.7 for uniform; with γ=0\gamma = 0, 93.693.6 versus 60.360.3; with γ=1\gamma = 1 but a=b=0.05a = b = 0.05, set AA is too small to catch large gradients and GOSS loses again, 96.096.0 versus 87.887.8. 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 ⌊1/η⌋\lfloor 1/\eta \rfloor iterations, because gradients are not concentrated initially (precisely case γ=0\gamma = 0). It sorts by ∣gihi∣\abs{g_i h_i}, not ∣gi∣\abs{g_i}. 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 =0.2= 0.2 and other_rate =0.1= 0.1.

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, 0.52240.5224 versus 0.51820.5182; at 0.4, 0.52960.5296 versus 0.52670.5267; 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 G=(V,E)G = (V, E), construct data with one row per edge and one feature per vertex: feature vv is 1 in the row for edge ee if vv is an endpoint of ee, otherwise 0 (each feature is a row of GG‘s incidence matrix). Two features u,vu, v are simultaneously nonzero in some row if and only if edge {u,v}\{u, v\} exists. Thus a conflict-free bundle is exactly an independent set of GG, a partition into kk bundles is a coloring with kk 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 KK; if none fits, open a new one. With K=0K = 0 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 Δ+1\Delta + 1 colors, with Δ\Delta maximum degree, and approximating chromatic number within factor n1−εn^{1 - \eps} is NP-hard for every ε>0\eps > 0 (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 γ\gamma of each bundle’s rows can conflict, the paper bounds the training accuracy effect by O([(1−γ)n]−2/3)\bigO([(1 - \gamma)n]^{-2/3}). 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 O(d2)\bigO(d^2), 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 O(#datos×#variables)\bigO(\#\text{datos} \times \#\text{variables}) to O(#datos×#grupos)\bigO(\#\text{datos} \times \#\text{grupos}). 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.

InteractiveEFB as graph coloring
Conflict graph (color = bundle)
31112112212A1A2A3A4B1B2B3C
Sparse matrix and merged columns
A1A2A3A4B1B2B3C111120013021410250016103723081129003102101122012220131021423015001160211700118023G1G2G3
G1: B3 → 1, A4 → 2G2: C → 1, B1 → 2, B2 → 3G3: A3 → 1, A1 → 2, A2 → 3
feature 8 of 8: B2
0
Search order (by degree)B3, C, A3, A4, B1, A1, A2, B2
Bundles3 (of 8 features)
Histogram cost: rows × columns18 × 8 = 144 → 18 × 3 = 54
Rows with conflict (information lost)0
B2 goes to bundle 2: it shares no nonzero row with it.
An 18-row, 8-binary-feature matrix from an explicit model: A1–A4 are one-hot for a four-level category (exactly one is 1 per row), B1–B3 indicate another category with a reference level (at most one is 1), and C is randomly 1 in one in four rows. Left, the conflict graph: an edge joins features simultaneously nonzero at least once, with the count of those rows. The greedy algorithm visits features by degree and colors each with the first compatible bundle. Right, the matrix and, on completion, merged columns: each cell says which feature in the bundle was nonzero (red border: conflict). Play the algorithm step by step and raise KK.

With K=0K = 0 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 KK 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 γ\gamma in the library.

Categorical features in LightGBM

A categorical with kk levels has 2k−1−12^{k - 1} - 1 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 k−1k - 1 respecting the ordering of target means by level. LightGBM applies the second-order version at each node: sort levels by ∑g/∑h\sum g / \sum h of node rows (with cat_smooth added to Hessian) and scan as if numeric, at cost O(klog⁡k)\bigO(k \log k).

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 ∑g/∑h\sum g / \sum h 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 =4= 4 (with 4 or fewer levels, one level versus rest), cat_smooth =10= 10, cat_l2 =10= 10 (specific L2 regularization for categorical splits), min_data_per_group =100= 100 (minimum rows per group of levels), and max_cat_threshold =32= 32 (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:

x^k=∑j∈Dk1[xj=xk] yj+a p∑j∈Dk1[xj=xk]+a,\hat x_k = \frac{\sum_{j \in \mathcal{D}_k} \ind[x_j = x_k]\, y_j + a\, p}{\sum_{j \in \mathcal{D}_k} \ind[x_j = x_k] + a},

with pp the prior (usually global mean of yy), a>0a > 0 its weight, and Dk\mathcal{D}_k the set of rows used to encode row kk. Naive (greedy) TS uses all: Dk=D\mathcal{D}_k = \mathcal{D}. Here is the leak: x^k\hat x_k contains yky_k.

The paper takes this to an extreme. Suppose all levels are distinct (an identifier) and P(y=1∣x)=0.5\Pr(y = 1 \given x) = 0.5 everywhere: the feature is useless. In training, each row is the only one of its level and x^k=(yk+ap)/(1+a)\hat x_k = (y_k + ap)/(1 + a), so one split at t=(0.5+ap)/(1+a)t = (0.5 + ap)/(1 + a) classifies perfectly. In test all levels are new, x^=p\hat x = p and the model is right half the time. The distribution of x^\hat x conditional on yy differs between training and test, a conditional shift, and the paper formulates the property that should hold:

P1. E[x^∣y=v]=E[x^k∣yk=v]\E[\hat x \given y = v] = \E[\hat x_k \given y_k = v]: 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: Dk=D∖{k}\mathcal{D}_k = \mathcal{D} \setminus \{k\}. It seems to solve it but does not. If the categorical is constant and there are n+n_+ ones, x^k=(n+−yk+ap)/(n−1+a)\hat x_k = (n_+ - y_k + ap)/(n - 1 + a): rows with yk=1y_k = 1 receive a slightly lower value than those with yk=0y_k = 0, and threshold t=(n+−0.5+ap)/(n−1+a)t = (n_+ - 0.5 + ap)/(n - 1 + a) separates them all. Within each level the value reveals the label.
  • Cross-validation (kk 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 (k−1)/k(k - 1)/k of them.
InteractiveTarget-statistic leakage and its remedy
Valor de la TS de 300 filas de cada conjunto, separadas por etiqueta
entrenamientoprueba
  • y=1y = 1
  • y=0y = 0
Logistic loss by boosting round
  • training
  • test
  • Bayes (test)
Gain: xx 36 %, categorical 64 %
Categorical encoding
300
1.0
Share of gain attributed to the categorical feature64.4 %
Training loss0.407
Test loss0.948
Bayes test loss (minimum possible)0.570
Each row’s TS includes its own label with weight 1/(nc+a)≈0.231/(n_c + a) \approx 0.23 in the mean. With about 3 rows per level, training rows with y=1y = 1 shift right but test rows do not: the model attributes 64 % of gain to pure noise.
Explicit model with 1000 training and 2000 test rows: x∼N(0,1)x \sim \Normal(0, 1), a categorical with KK equally probable levels and no effect, and y∼Bern⁡(σ(1.2x−0.3))y \sim \Bern(\sigmoid(1.2x - 0.3)). The categorical is encoded by a smoothed mean (prior pp and weight aa) computed over all rows (naive), all except itself (leave-one-out), the other four folds (cross-fitting), or preceding rows in a random permutation (ordered); test always uses all training rows. A histogram logistic GBDT (32 bins, 40 depth-3 trees, η=0.2\eta = 0.2, λ=1\lambda = 1) trains on (x,x^)(x, \hat x). Left, encoding values of 300 rows from each set separated by label; right, training and test loss per round versus Bayes loss, and categorical's share of total gain. Change encoding and level count.

With naive encoding and 300 levels (about 3.3 rows per level), a row’s own label weighs 1/(nc+a)≈0.231/(n_c + a) \approx 0.23 in its mean: training rows with y=1y = 1 shift right of those with y=0y = 0, unlike test. The model gives a pure-noise feature 64% of gain, and test loss (0.9480.948) moves away from Bayes (0.5700.570) while training falls to 0.4070.407. With 1000 levels it is worse (87% and 1.6441.644); 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 1/(nc−1+a)≈0.011/(n_c - 1 + a) \approx 0.01, 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 1.0071.007. 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 KK), and test loss is within 0.020.02 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 Ft−1F_{t-1} was trained on all rows, and round tt gradients are computed on those same rows. The paper describes a chain of shifts:

  1. the distribution of gt(xk,yk)∣xkg_t(\vb{x}_k, y_k) \given \vb{x}_k on a training row (counting randomness in other data) differs from gt(x,y)∣xg_t(\vb{x}, y) \given \vb{x} on a new example;
  2. therefore tree hth_t fitted to those gradients is biased relative to the tree fitted with new-data gradients;
  3. and that worsens generalization of FtF_t.

It calls this prediction shift and proves it in the simplest possible case.

Term O(2−n)\bigO(2^{-n}) covers the exponentially unlikely case of a leaf with no examples. The proof idea, in appendix A, fits in two lines. With ξst\xi_{st} the count of rows with x=(s,t)\vb{x} = (s, t), the first stump is h1(s,⋅)=c1s+c2 ξs1/(ξs0+ξs1)h_1(s, \cdot) = c_1 s + c_2\, \xi_{s1}/(\xi_{s0} + \xi_{s1}). On a new example, E[h1(x)]=c1x1+c2/2\E[h_1(\vb{x})] = c_1 x_1 + c_2/2. On a training row, the row itself is inside ξs1\xi_{s1}: if it has x2=1x_2 = 1, it raises its leaf’s fraction, and the paper obtains E[h1(xk)]=c1x1+c2/2−c2(2x2−1)/n+O(2−n)\E[h_1(\vb{x}_k)] = c_1 x_1 + c_2/2 - c_2(2x_2 - 1)/n + \bigO(2^{-n}). Training residuals are shrunk toward zero, and the second stump fits them and inherits shrinkage. Bias is inversely proportional to nn and proportional to c2c_2: it matters for small datasets and strong relationships. In the lab you reproduce it by Monte Carlo: with c1=2c_1 = 2, c2=1c_2 = 1 and n=10n = 10, measured bias over x2=1x_2 = 1 is −0.0544-0.0544 versus the theorem’s −1/18=−0.0556-1/18 = -0.0556 (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 n=100n = 100 bias is 0.5% of c2c_2. 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

yky_k does not enter x^k\hat x_k, and x^k\hat x_k is calculated from rows as foreign to row kk 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 kk‘s residual to be unshifted, the model computing it cannot have seen row kk. The paper’s algorithm 1 follows this literally: maintain nn supporting models M1,…,MnM_1, \dots, M_n, where MiM_i trains only on the first ii permutation rows, and row kk‘s residual uses Mσ(k)−1M_{\sigma(k) - 1}, which has not seen it. This multiplies cost and memory by nn, 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, c2/2=0.5c_2/2 = 0.5 for rows with x2=1x_2 = 1, 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 (−0.6 %-0.6\,\%) and Kick (−0.2 %-0.2\,\%), 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 (σcat=σboost\sigma_{\text{cat}} = \sigma_{\text{boost}}): if different, row ii‘s label could enter model MiM_i 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 dd 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-dd symmetric tree has 2d2^d leaves but only dd chosen splits, versus 2d−12^d - 1 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.
InteractiveSymmetric trees as a table
Leaf regions (drag the point)
021357x₁x₂
The same tree drawn as a tree: one test per level
level 0: x₁ > 0.35 → b0 = 1level 1: x₂ > 0.60 → b1 = 0level 2: x₁ > 0.70 → b2 = 100.604empty21.136empty11.0750.6631.6171.19
  • level 0
  • level 1
  • level 2
  • leaf value (darker color means larger value)
0.35
0.60
Level-2 feature
0.70
leaf=b0+2b1+4b2=1+2⋅0+4⋅1=5\text{leaf} = b_0 + 2b_1 + 4b_2 = 1 + 2\cdot 0 + 4\cdot 1 = 5
Point (x1,x2)(x_1, x_2)(0.80, 0.30)
Bits (b0,b1,b2)(b_0, b_1, b_2)(1, 0, 1)
Binary index b2b1b0b_2 b_1 b_0101 = 5
Leaf value0.659
Reachable leaves6 of 8
All three bits are computed at once, without dependent branches, and the leaf is read from the table. With two features and three levels, one repeats: levels 0 y 2 test x1x_1, and combinations such as x1≤0.35x_1 \le 0.35 with x1>0.70x_1 > 0.70 never occur. Thus 2 of 8 table entries are unreachable; with three distinct features all 8 would be regions.
A depth-3 symmetric tree over (x1,x2)∈[0,1]2(x_1, x_2) \in [0, 1]^2: level 0 tests x1>t0x_1 > t_0, level 1 tests x2>t1x_2 > t_1, and level 2 the feature you choose at threshold t2t_2. Each leaf is mean f(x)=sin⁡(3x1)+x22f(\vb{x}) = \sin(3x_1) + x_2^2 over its region (what a tree fitted without noise to uniform data would give). Left, regions with indices and a draggable point; right, the same tree drawn as a tree, highlighting the point's path and three bits. Move the point and watch bits and index change. With two features and three levels one feature always repeats: find which two table entries are empty and why, and change the level-2 feature.

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 sin⁡(3x1)\sin(3x_1) changes quickly; a symmetric one cannot. When two levels test the same feature, some bit combinations are impossible (x1≤0.35x_1 \le 0.35 and x1>0.7x_1 > 0.7 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 bb of feature kk goes to cell kB+bkB + b), and the subtraction check.

[ ]Discretize, build histograms and subtractBrowser
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 λ\lambda, stored without 12\frac12 like LightGBM and scikit-learn. On top is the boosting loop, optional GOSS or uniform sampling and gain importance.

[ ]Minimal LightGBM: leaves, subtraction and GOSSBrowser
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 10−910^{-9}, rounding from scikit-learn storing gradients and Hessians in float32; in classification, on the order of 10−810^{-8} on all training rows. But new classification points show a difference of 0.090.09, with an instructive cause. At a node of tree 30 no row has x2=30x_2 = 30: bin 30 is empty and splitting at “bin ≤29\le 29” or “bin ≤30\le 30” 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 x2=30x_2 = 30 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.

[ ]Exact search versus histogramsBrowser
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 (0.41210.4121) is even slightly lower than exact (0.41690.4169). 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 sin⁡(2x0)\sin(2x_0). Time falls severalfold: both algorithms are vectorized, but exact sorts every feature in every leaf (O(mlog⁡m)\bigO(m \log m)) while histogram only sums (O(m)\bigO(m)) 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 3.07 n3.07\,n rows versus 7.58 n7.58\,n, 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.

[ ]Leaf-wise versus level-wise growthBrowser
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 n=4000n = 4000 and 8 leaves, leaf-wise clearly wins (0.12990.1299 validation versus 0.14270.1427): 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 (0.13730.1373 versus 0.13500.1350). With n=400n = 400, removing min_data_in_leaf leaves single-row leaves: training error falls to 0.00150.0015 and validation rises to 0.19970.1997, worst of all. The last n=400n = 400 line confirms the section result: with num_leaves =26= 2^6 and max_depth =6= 6, 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 n=10 000n = 10\,000: mean and standard deviation of G^L\hat G_L across 3000 batches versus exact value and variance formula, for GOSS and equal-size uniform sampling.

[ ]GOSS versus uniform sampling: variance of G_LBrowser
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 GLG_L within Monte Carlo error (one standard deviation divided by 3000≈55\sqrt{3000} \approx 55 with 3000 batches), and measured deviations match the formula. The theorem’s criterion predicts the winner in all four cases. With γ=0\gamma = 0 all gradients equal ±0.5\pm 0.5, removing the largest does not reduce variance (Sr2/S2S_r^2/S^2 near 1) and GOSS clearly loses. With γ=1\gamma = 1, a=0.2a = 0.2 and b=0.1b = 0.1, removing the top 20% leaves only 16% of variance, far below threshold 0.417, and GOSS wins. With a=b=0.05a = b = 0.05 set AA is too small and large gradients remain: the threshold is less demanding but Sr2/S2S_r^2/S^2 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.

[ ]Greedy exclusive feature bundlingBrowser
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.

[ ]Four target statistics and what they do to importanceBrowser
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 (0.43030.4303 versus 0.65710.6571). 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 0.03180.0318 and test loss shoots to 1.46691.4669. 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), xx is most important again and test loss is closest to Bayes (0.58260.5826 and 0.57540.5754 versus 0.55310.5531).

Prediction shift, measured

Finally theorem 1 by Monte Carlo, with c1=2c_1 = 2 and c2=1c_2 = 1: classical model (both stumps with same sample), a second independent sample for the second stump, and ordered residuals.

[ ]Prediction-shift theorem by Monte CarloBrowser
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 x2=1x_2 = 1 are below 0.5 (0.300.30, 0.400.40 and 0.480.48 for n=5n = 5, 10 and 50): the first link, training gradient shifted relative to a new example. The second stump fits them and FF bias matches theorem −1/(2(n−1))-1/(2(n - 1)) 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 FF bias with them does not vanish: its sign reverses and for n=50n = 50 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.

[ ]LightGBM on Amazon: four ways to pass categoricalsLocal GPU
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=[]))
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]CatBoost: Ordered versus Plain, GPU and GOSS in the libraryLocal GPU
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}")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 =4= 4, cat_smooth =10= 10, top_rate =0.2= 0.2 and other_rate =0.1= 0.1.

Four ways to give categoricals to LightGBM. Same split and early stopping:

EncodingTest lossAUCTraining lossTrees
integers as ordinal0.16950.82650.1120250
native categoricals0.15570.85270.089181
naive TS0.18670.80120.082917
ordered TS0.15690.86460.1284133

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 0.15690.1569 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 (0.15570.1557) and trail in AUC. Ordinal identifiers need 250 trees to reach 0.16950.1695: 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 =3= 3 and one_hot_max_size =2= 2. 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 0.1337±0.00030.1337 \pm 0.0003 in Plain and 0.1352±0.00090.1352 \pm 0.0009 in Ordered (three seeds): on Amazon Plain is slightly better, as in paper table 3 (−0.6 %-0.6\,\%). With 10% of data, 0.2032±0.00410.2032 \pm 0.0041 versus 0.2024±0.00520.2024 \pm 0.0052 (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: 0.13370.1337 versus 0.15570.1557 or 0.15690.1569, 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 (0.13980.1398 versus 0.13270.1327), 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 (a=0.2a = 0.2, b=0.1b = 0.1) versus uniform subsampling:

RegimeAll rowsGOSSUniform 30%
high noise (scale 1)0.45250.46280.4581
low noise (scale 3)0.20350.20430.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

NumericWeight of small-gradient rows
In GOSS with a=0.2a = 0.2 and b=0.1b = 0.1, by what number are gradients and Hessians of sampled small-gradient rows multiplied?
Quiznum_leaves for max_depth = 7
You want a LightGBM tree with 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?
NumericHow many rows a tree costs
A depth-3 level-wise tree on n=8000n = 8000 rows splits each node into 25% and 75% of its rows. To find splits of levels 0, 1 and 2 you need their histograms. Building the root directly and at each split only the smaller child's histogram (larger by subtraction), how many rows do you scan in total?
ProofGOSS does not bias sums
Prove: In GOSS with fractions aa and bb, let AA be the fixed set of anan rows with greatest ∣gi∣\abs{g_i} and BB a simple random sample of bnbn rows from AcA^c. For a fixed split, estimator G^L=∑ALgi+1−ab∑BLgi\hat G_L = \sum_{A_L} g_i + \tfrac{1 - a}{b}\sum_{B_L} g_i satisfies E[G^L]=GL\E[\hat G_L] = G_L.
0
Write GL=∑ALgi+∑ALcgiG_L = \sum_{A_L} g_i + \sum_{A^c_L} g_i and treat membership in BB as random indicator variables.

Step 1 of 4. How do you rewrite the random part of G^L\hat G_L?

CodeBuild and subtract histograms
Implement 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, parent
Shift+Enter to run
NumericThe threshold revealing the label
A category has 101 rows, 60 with y=1y = 1. With leave-one-out TS without prior (a=0a = 0), rows with y=1y = 1 get one value and those with y=0y = 0 another. What threshold halfway between them perfectly separates labels?
CodeOrdered target statistics
Implement ordered_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 (∑yj+a p)/(m+a)(\sum y_j + a\,p)/(m + a), where sum and count mm 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 out
Shift+Enter to run
QuizWhat the EFB theorem says
The LightGBM paper proves grouping features into the fewest exclusive bundles is NP-hard. What follows?
NumericSize of the shift
In CatBoost theorem 1's example, with c2=3c_2 = 3 and n=31n = 31 examples, and both stumps trained on the same sample, what is bias E[F(x)]−f∗(x)\E[F(\vb{x})] - f^*(\vb{x}) at a point with x2=1x_2 = 1 (ignoring O(2−n)\bigO(2^{-n}))?
QuizWhy a symmetric tree predicts quickly
Why are CatBoost's symmetric trees fast at inference?
QuizWhat Ordered mode does
In CatBoost's implementation, which training parts use ordered supporting models (which have only seen preceding rows in a permutation)?

Summary

Key idea
LightGBM and CatBoost retain XGBoost’s Newton gain and change two different things. LightGBM reduces evaluation cost: few-bin histograms with sibling subtraction, leaf-wise growth, fewer rows with GOSS (all large-gradient rows plus a reweighted sample of the rest) and fewer columns with EFB (merged exclusive features, greedy graph coloring). CatBoost corrects bias: naive TS and gradients computed with a model that saw the row use its own label, and random-permutation ordering (ordered TS and boosting, over symmetric trees) ensures each row uses only history.
  • Histograms. Discretizing once into up to 255 bins (one byte per value) turns split search into bin sums: O(∣I∣d)\bigO(\abs{I}d) to build and O(Bd)\bigO(Bd) to scan. Building only the smaller child and subtracting scans at most n/2n/2 rows per level and each row at most 1+log⁡2n1 + \log_2 n 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 =D= D, num_leaves must not exceed 2D2^D and should stay below; with num_leaves =2D= 2^D and all splits valid, it matches level-wise.
  • GOSS. With weight (1−a)/b(1 - a)/b, gradient and Hessian sums are unbiased Horvitz–Thompson estimates; nonlinear gain is optimistic. GOSS has lower variance than uniform sampling if and only if Sr2/S2<b/((1−a)(a+b))S_r^2/S^2 < b/((1 - a)(a + b)): when gradients are concentrated.
  • EFB. Optimal bundling is NP-hard (equivalent to conflict-graph coloring); degree-greedy with tolerated conflicts reduces cost from O(nd)\bigO(n d) to O(n⋅#grupos)\bigO(n \cdot \#\text{grupos}) 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 1/(nc−1+a)1/(n_c - 1 + a). Cross-fitting and ordered TS do not see the row’s label.
  • Prediction shift. Reusing data to calculate gradients biases the model by −c2(x2−12)/(n−1)-c_2(x_2 - \frac12)/(n - 1) 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 Ordered gain is small and concentrated on small datasets.
  • Symmetric trees. One split per level: the leaf is the binary number of dd independent comparisons, enabling fast vectorized inference and a more regularized tree family.