Module contents
Lesson 20 of 24Advanced 100 min

Gradient boosting in practice: comparison, tuning and constraints

Turn earlier theory into engineering judgment. Compare XGBoost, LightGBM, CatBoost and HistGradientBoosting in design, defaults and behavior; establish a staged tuning recipe with early stopping and a controlled budget; and introduce monotonic and interaction constraints, DART and custom losses. Finish with a reproducible benchmark on the local GPU.

After this lesson you can

  • Develop a reasoned comparison of XGBoost, LightGBM and CatBoost (growth, splits, categoricals, missing values, regularization and GPU).
  • Apply staged tuning: learning rate and early stopping, tree complexity, sampling and regularization.
  • Impose monotonic and interaction constraints and explain their implementation in split search.
  • Use DART and explain when it helps against overspecialization of late trees.
  • Design a fair library benchmark with nested CV, equal tuning budgets and multiple seeds.

Before you start

Motivation: tuning matters more than the library

You already know the inner workings of the three libraries dominating tabular data: XGBoost’s regularized objective and Newton gain, LightGBM’s histograms, leaf-wise growth and GOSS, and CatBoost’s ordered boosting and symmetric trees. This lesson turns theory into engineering judgment: which library to choose and why, how to tune without wasting budget, how to encode domain knowledge (monotonicity, allowed interactions), and how to compare libraries honestly.

Start with an awkward question: how much does the library matter? Less than tuning it, apparently. Probst, Boulesteix and Bischl (JMLR 2019) measured tunability of six algorithms on 38 OpenML datasets: mean AUC improvement moving from reference values to each dataset’s best tuning. For XGBoost, compared with package defaults, mean gain is 0.0430.043 AUC (paper table 2); compared with “optimal defaults” learned from the 38 datasets (η=0.018\eta = 0.018, 4168 trees, depth 13, subsample =0.839= 0.839, colsample_bytree =0.752= 0.752; table 3), it falls to 0.0140.014. In other words, better starting values already recover two thirds of per-dataset tuning’s benefit, and one should not simply stick to package defaults. This lesson’s tuning interactive shows it on Higgs with LightGBM, and the local lab measures four libraries under the same protocol.

By the end you will understand design differences between XGBoost, LightGBM, CatBoost and scikit-learn HistGradientBoosting; follow a phased tuning recipe and know when it fails; implement monotonic and interaction constraints in your own GBDT and prove why they work; know when to try DART; and have a reproducible local benchmark with nested CV, equal budgets and several seeds.

Four libraries, one reasoned comparison

All four implement the same algorithm, tree-based Newton boosting: each round loss gradients gig_i and Hessians hih_i, a tree maximizing second-order gain and leaves with weight −G/(H+λ)-G/(H + \lambda). Differences lie in five design decisions, most seen in the preceding two lessons.

DecisionXGBoost 3.4LightGBM 4.7CatBoost 1.2HistGradientBoosting (scikit-learn 1.9)
Growthlevel-wise, max_depth 6; optional grow_policy="lossguide"leaf-wise, num_leaves 31, unlimited depthsymmetric (one split per level), depth 6leaf-wise, max_leaf_nodes 31
Splitsdefault hist, 256 bins; optional exact and approx255-bin histogram; optional GOSS and EFB for sparse features254 CPU boundaries, 128 GPU255-bin histogram
Categoricalsenable_categorical: gradient partition, one-hot below 4 levelsgradient partition with smoothing (cat_smooth 10) and minimum group sizeordered target statistics and categorical combinationsgradient partition, at most 255 levels
Missinglearned default direction at each nodelearned directionnan_mode="Min": missing is less than all valueslearned direction
Default regularizationη=0.3\eta = 0.3, λ=1\lambda = 1, min_child_weight 1η=0.1\eta = 0.1, λ=0\lambda = 0, min_data_in_leaf 20η\eta chosen from data, l2_leaf_reg 3, 1000 treesη=0.1\eta = 0.1, λ=0\lambda = 0, min_samples_leaf 20; automatic early stopping above 10 000 rows
GPUdevice="cuda"only with GPU- or CUDA-compiled binarytask_type="GPU"no

Table defaults were read from the libraries themselves (using save_config, model parameter dump, get_all_params and get_params) in the course environment. They change across versions (XGBoost switched to default hist in version 2.0), so the local lab begins by printing versions. This is the reasoned GBDT library comparison: not a list of advantages, but different inductive biases and defaults. On the same data with nothing changed, all four train different models, so comparing defaults does not determine which is better.

InteractiveLibrary differences explorer
XGBoost
LightGBM
CatBoost
HistGB
Growth
Splits
Categorical features
Missing values
Default regularization
GPU
Growth in LightGBM: leaf-wise (num_leaves 31, no depth limit)
8
level-wise: training R2R^2 with 8 leaves0.739
leaf-wise: training R2R^2 with 8 leaves0.875
symmetric: training R2R^2 with 6 leaves0.727

All three policies use the same criterion (least squares) and the same number of leaves. Leaf-wise growth spends splits where they reduce error most, here at the bump (orange circle); the symmetric tree uses one split per level for all leaves, so it adapts least but is very cheap to evaluate and regularizes.

Each row is a design decision and each column a library. Clicking a cell displays a simulation of that decision with an explicit model calculated in your browser. Growth: a regression tree with LL leaves on 400 points from [0,1]2[0, 1]^2 with y=x1+3⋅1[bulto]+N(0,0.32)y = x_1 + 3\cdot\ind[\text{bulto}] + \Normal(0, 0.3^2), grown level-wise, leaf-wise or symmetrically under the same criterion. Splits: gain of every exact threshold of a lognormal feature versus a BB-quantile-bin histogram. Categoricals: a CC-level feature with small effect encoded using greedy or ordered statistics, or split by gradient. Missing: best split when missing values cluster at high values. Regularization: factor H/(H+λ)H/(H + \lambda) shrinking a leaf weight and minimum leaf sizes. GPU: times measured once in the local lab's short run.

Three rows deserve attention because they explain most benchmark differences.

Growth. With the same leaves, leaf-wise growth reduces training loss more than level-wise because splits go where gain is greatest; symmetric adapts least because one split serves a whole level. In the eight-leaf growth simulation, training R2R^2 is greater leaf-wise than level-wise and smaller with the symmetric tree. This costs variance: leaf-wise with high num_leaves and no min_data_in_leaf builds deep branches isolating a few rows, whereas symmetry acts as structural regularization. CatBoost therefore often works well without complexity tuning, while LightGBM is most sensitive to num_leaves.

Categoricals. This row has the greatest practical consequences. XGBoost, LightGBM and HistGB sort categorical levels by mean node gradient and find the best split in that order, Fisher’s exact trick for squared loss seen in CART categorical splits. With many levels and few rows per level, ordering fits noise; LightGBM limits this with cat_smooth, cat_l2 and min_data_per_group. CatBoost instead replaces each level by ordered target statistics, which do not use the row’s label. In the simulation with 400 levels and 2000 rows, greedy statistics (including the row’s label) look excellent in training and are worse than dropping the feature on test; ordered statistics do not deceive.

Missing values. XGBoost, LightGBM and HistGB learn at each split which side receives missing values, using sparsity-aware search. CatBoost defaults to treating them as below all values (nan_mode="Min"): one split can isolate them or send them with low values, but cannot group them with high values. If missing means “high” (high earners do not disclose), a shallow CatBoost tree needs an extra split.

A phased tuning recipe

A GBDT has around ten consequential hyperparameters, and evaluation budget almost never permits exploring all at once. Practice has converged on an order grouping controls by role. This is the phased GBDT tuning recipe:

  1. Protocol first. Separate training, validation (early stopping and hyperparameter selection) and test (reporting), or use nested CV. Early stopping is tuning: the chosen tree count is fitted to validation.
  2. Moderate rate and early stopping. Set η\eta between 0.050.05 and 0.10.1, a generous maximum tree count, and early stopping with patience 50 to 200 rounds. Thereafter tree count is not tuned: stopping chooses it.
  3. Tree complexity. num_leaves or max_depth, with minimum leaf size (min_data_in_leaf, min_child_weight, min_samples_leaf). This phase moves error most.
  4. Sampling. Row fraction (subsample, bagging_fraction) and column fraction (colsample_bytree, feature_fraction): stochastic boosting reduces variance and speeds up.
  5. Regularization. λ\lambda (L2 on leaf weights), α\alpha (L1) and γ\gamma (minimum split gain, min_split_gain in LightGBM).
  6. Lower rate last. Divide η\eta by 2 to 10 and retrain with early stopping: tree count grows inversely and error falls a little.

Names vary between libraries, but roles do not:

RoleXGBoostLightGBMCatBoostHistGB
ratelearning_rate (eta)learning_ratelearning_ratelearning_rate
treesn_estimators + early_stopping_roundsnum_iterations + early_stoppingiterations + od_waitmax_iter + n_iter_no_change
tree sizemax_depth, max_leavesnum_leaves, max_depthdepthmax_leaf_nodes, max_depth
minimum leafmin_child_weight (Hessian)min_data_in_leaf, min_sum_hessian_in_leafmin_data_in_leaf (non-symmetric)min_samples_leaf
rowssubsamplebagging_fraction + bagging_freqsubsample (with bootstrap_type)none
columnscolsample_bytree, _bylevel, _bynodefeature_fraction, feature_fraction_bynodersm (CPU only)max_features (per node)
L2, L1, minimum gainlambda, alpha, gammalambda_l2, lambda_l1, min_gain_to_splitl2_leaf_regl2_regularization

Watch a units trap: XGBoost’s min_child_weight is a sum of Hessians, not rows. With logistic loss each row contributes h=p(1−p)≤0.25h = p(1 - p) \le 0.25, so min_child_weight =1= 1 requires at least 4 rows in a leaf with p=0.5p = 0.5 and 12 with p=0.9p = 0.9. LightGBM’s min_data_in_leaf counts rows.

Rate and tree count go together

Why not tune η\eta and tree count simultaneously? With early stopping the latter is almost a function of the former. With shrinkage, each round does

Ft+1=Ft+η ft,ft≈aˊrbol ajustado a −∇FR^(Ft),F_{t+1} = F_t + \eta\, f_t, \qquad f_t \approx \text{árbol ajustado a } -\grad_F \hat R(F_t),

an Euler step of size η\eta for differential equation  ⁣dF ⁣ds=f(F(s))\tfrac{\dd F}{\dd s} = f(F(s)) in continuous “time” ss. If η\eta is small, the model after tt rounds depends on tt and η\eta almost solely through product s=ηts = \eta t: the same path traversed in shorter steps. Early stopping stops at time s∗s^* depending on data, not η\eta, so

T∗(η)≈s∗η.T^*(\eta) \approx \frac{s^*}{\eta}.

This is a heuristic, not a theorem: the fitted tree is a discontinuous function of gradients, and with large η\eta steps stop following the path (each tree overshoots and the next corrects). The lab’s first cell checks this: training error at fixed ηt\eta t barely changes between η=0.1\eta = 0.1, 0.050.05 and 0.0250.025, separating at η=0.4\eta = 0.4. In the interactive grid, the final recipe configuration with 2000 rows stops at 78 trees with η=0.1\eta = 0.1 and 390 with η=0.02\eta = 0.02: exactly factor 5.

Two practical consequences follow. Tuning η\eta and tree count as two search axes wastes budget: almost the whole grid lies far from diagonal ηT≈s∗\eta T \approx s^*. And lowering η\eta at the end requires raising maximum trees proportionately, or early stopping never gets to act.

What the experiment says

The following interactive simulates nothing: it is a table of 864 real LightGBM training runs on Higgs (OpenML 23512, 28 particle-physics numeric features), run locally for this lesson. Each cell is validation log-loss for grid configuration num_leaves ∈{4,8,16,31,64,128}\in \{4, 8, 16, 31, 64, 128\}, min_data_in_leaf ∈{2,10,40,160}\in \{2, 10, 40, 160\}, feature_fraction and bagging_fraction ∈{0.5,0.75,1}\in \{0.5, 0.75, 1\}, and lambda_l2 ∈{0,1,10,100}\in \{0, 1, 10, 100\}, with η=0.1\eta = 0.1, 50-round early stopping on 10 000 validation rows and testing on another 20 000. The grid was computed twice, with 2000 and 20 000 training rows. An “evaluation” reads a cell, allowing equal-budget strategy comparison without waiting.

InteractivePhased tuning versus random search
Phase 1, complexity
0.5970.5920.5960.5990.6060.6270.5940.5900.5930.5980.6070.6200.5940.5910.5900.5970.5960.5960.5950.5930.5940.5940.5940.59448163164128num_leaves21040160
rows: min_data_in_leaf
Phase 2, sampling
0.59910.59730.59550.59620.59140.59030.59130.59070.59020.50.751feature_fraction0.50.751
rows: bagging_fraction
Phase 3, regularization: lambda_l2
0.5900.5910.5900.5930110100lambda_l2
Best validation log-loss found versus evaluations (2000 rows). Current recipe configuration: num_leaves 8, min_data 10, ff 1, bf 1, λ 10.
defaultgrid optimum
  • phased recipe
  • random search: median and 10%–90% band
  • selected budget
Training rows
Phase order
35
Recipe: best validation log-loss0.5900
Random: median [10%, 90%]0.5902 [0.5887, 0.5910]
LightGBM defaults (31 leaves, 20 per leaf)0.5968
Optimum of 864 configurations0.5871
Test: recipe / random median / default0.5833 / 0.5846 / 0.5929
Trees for the recipe configuration (η = 0.1)78
Final phase, same configuration with η = 0.02: validation / test / trees0.5891 / 0.5821 / 390
Seeds 1 to 5no sampling: identical
The recipe finishes in 35 evaluations with 0.5900 validation loss, 0.0029 from the optimum of 864 configurations. With 35 evaluations, 37% of random searches match or beat it.
Above, the recipe's three phases as heatmaps: complexity (num_leaves × min_data_in_leaf), sampling (feature_fraction × bagging_fraction), regularization (lambda_l2). Each evaluates all cells of its slice with remaining controls at prior phases' choices (initially LightGBM defaults with min_data_in_leaf = 10) and keeps the best (orange border); deeper blue means lower validation log-loss. Below, best validation log-loss against evaluation count: recipe (blue) and 2000 random searches without replacement over 864 configurations (median and 10%–90% band). Every number comes from actual LightGBM 4.7 Higgs training with seed 0. Completing the recipe reveals the final η = 0.02 phase and final-configuration variation across seeds.

There are four readings, each contradicting a common belief.

Defaults lose, more so with few data. With 2000 rows LightGBM defaults yield 0.59680.5968 validation and 0.59290.5929 test; the full recipe, with final η=0.02\eta = 0.02 phase, gives 0.58210.5821 test. With 20 000 rows the gap halves (0.54380.5438 versus 0.53850.5385). The first map shows why: with 2000 rows, 31 leaves are too many and optimal complexity is 8; with 20 000, trees of 31–128 leaves with large leaves (min_data_in_leaf 160) are best. Appropriate complexity grows with data, and defaults target medium datasets.

The recipe ties random search, not crushes it. With 35 evaluations, the recipe reaches 0.59000.5900 with 2000 rows and 0.54310.5431 with 20 000; median random search at equal budget reaches 0.59020.5902 and 0.54300.5430. This matches the Bergstra–Bengio argument seen in random search: when a few controls matter a lot and others little, random sampling explores those few well. The recipe’s advantage is not its final number but that each phase is interpretable (the first map shows how much complexity the data support) and needs no well-chosen joint search space.

Phase order changes the choice. Switch to “regularization first.” With 20 000 rows, reversed recipe ends at num_leaves 64, min_data_in_leaf 40, feature_fraction 0.750.75 and λ=100\lambda = 100, the optimum among 864 configurations (0.54140.5414); normal recipe at 31 leaves, 160 rows per leaf, no sampling and λ=100\lambda = 100 (0.54310.5431). Coordinate search is not order-invariant because controls interact: num_leaves, min_data_in_leaf and λ\lambda regulate the same thing, effective leaf size. With λ=100\lambda = 100 and Hessians around 0.250.25 per row, a 400-row leaf’s weight is halved, and under that shrinkage bigger trees become good again; if complexity is fixed with λ=0\lambda = 0, chosen trees are only optimal without regularization.

But the reverse order’s advantage is mostly luck. Its selected configuration uses feature_fraction =0.75= 0.75, making its result seed-dependent. With seed 0, used by the grid, it yields 0.54140.5414 validation; seeds 1–5 yield 0.54200.5420 to 0.54390.5439, an interval containing normal recipe’s deterministic 0.54310.5431. On test, reverse yields 0.53810.5381 with seed 0 and 0.53950.5395 to 0.54150.5415 with the other five; normal yields 0.53890.5389. With 2000 rows the same occurs: reverse wins validation (0.58870.5887 versus 0.59000.5900, with bagging_fraction 0.750.75), loses on other seeds (0.58880.5888 to 0.59280.5928) and loses on test (0.58440.5844 versus 0.58330.5833). This is winner’s bias: choosing the minimum of many noisy evaluations favors lucky configurations, small-scale validation overfitting. Two lessons: differences of a thousandth between sampled configurations lie within seed noise, and reported error must come from data and seeds unused in choices. If budget permits, make a second phase pass or tune complexity and λ\lambda together.

The final phase delivers. With the recipe’s final configuration and η=0.02\eta = 0.02, early stopping chooses 390 instead of 78 trees with 2000 rows, and 1037 instead of 221 with 20 000; test improves slightly in both (0.5833→0.58210.5833 \to 0.5821 and 0.5389→0.53850.5389 \to 0.5385). Small, cheap improvements: the phase moving error least but the only one needing no search.

What about Bayesian search? With budgets of tens of evaluations, model-based methods (Optuna’s TPE, Gaussian processes) often improve on random by concentrating trials near previous successes, and successive halving allocates budget better using tree count as a resource. The phased recipe remains useful as a starting point and to understand what moves error; for the final number use model-based search with the same budget across libraries, as in the local lab.

Monotonic constraints

In many problems the effect’s sign is known beforehand. All else equal, a higher-income customer should not be less likely to repay a loan; a larger home should not be worth less; higher risk should not reduce a premium. An unconstrained GBDT knows none of this: with noisy data, partial dependence curves are jagged and a customer’s score may fall after reporting higher income. In credit this is a model hard to justify to the customer and supervisor, even with good validation error.

Since the model sums trees with positive weights, F=F0+η∑tftF = F_0 + \eta \sum_t f_t, it suffices for each tree to be monotonic. The temptation is to enforce this locally: when searching for a split on feature jj, reject splits whose left weight exceeds right. This is insufficient. If the root splits on income with wL<wRw_L < w_R and each child later splits on age, “low income, high age” can exceed “high income, high age”: an older person’s score falls with higher income. The veto compares two children, but monotonicity compares leaves in different subtrees.

XGBoost and scikit-learn solve this by propagating bounds down the tree. Each node carries interval [ℓ,u][\ell, u] containing every weight in its subtree (root (−∞,∞)(-\infty, \infty)), and leaf weights are clipped to that interval: w=clip⁡(−G/(H+λ),ℓ,u)w = \operatorname{clip}(-G/(H + \lambda), \ell, u), also when calculating candidate split gains.

Proof

First, by induction from root, each node’s interval is nonempty and contained in its parent’s: wL,wR∈[ℓv,uv]w_L, w_R \in [\ell_v, u_v] because weights are clipped, so m∈[ℓv,uv]m \in [\ell_v, u_v] and intervals [ℓv,m][\ell_v, m] and [m,uv][m, u_v] are nonempty and within [ℓv,uv][\ell_v, u_v]. Since each leaf weight is clipped to its interval, all leaves of node vv‘s subtree have weights in [ℓv,uv][\ell_v, u_v].

Now take points x\vb{x} and x′=x+δej\vb{x}' = \vb{x} + \delta\vb{e}_j with δ>0\delta > 0, where jj has an increasing constraint. They travel together while splits use features other than jj, since they agree there. If they reach a leaf together, F(x)=F(x′)F(\vb{x}) = F(\vb{x}'). Otherwise they separate at first node vv sending them to different sides, which must split feature jj at threshold τ\tau such that xj<τ≤xj+δx_j < \tau \le x_j + \delta: x\vb{x} goes left and x′\vb{x}' right. x\vb{x}’s leaf is in the left subtree and weighs at most mm; x′\vb{x}'‘s is right and weighs at least mm. Hence f(x)≤m≤f(x′)f(\vb{x}) \le m \le f(\vb{x}').

A sum of increasing functions with positive coefficients is increasing, so model F0+η∑tftF_0 + \eta\sum_t f_t is too. With several constrained features, the argument uses only the first separating node, which splits on the sole feature where the two points differ.

∎

Notice what the proof does not use: condition wL≤wRw_L \le w_R is unnecessary for monotonicity (bounds already ensure it); it avoids accepting splits whose unclipped weights go against it and become two equal leaves at mm with no contribution. And note the cost: midpoint is conservative. A left subtree whose weights all lie far below mm did not require such a low bound on the right. LightGBM offers three monotone_constraints_method choices: basic, fixed bounds, which documentation says does not slow training but “over-constrains” predictions; intermediate and advanced restrict far less and should improve results substantially, at some speed cost. XGBoost documentation warns of another effect: hist or approx has few candidate thresholds, and constraints can eliminate all, leaving unnecessarily shallow trees; increase max_bin to remedy it.

InteractiveEnforcing monotonicity
Repayment probability versus income: partial dependence (thick), 10 ICE curves (thin), and observed rate by decile (dots)
without constraint
  • Unconstrained GBDT
  • with constraint
  • true partial dependence
  • observed rate by decile
Constrained and plotted variable
800
150
Unconstrained validation log-loss0.6910
Constrained validation log-loss0.6910
True-model log-loss (bound)0.5972
Training: without and with constraint0.6918 and 0.6918
Decreasing ICE segments (of 13350)0 without, 0 with
Without the constraint, partial dependence decreases in 0 of 89 grid segments and ICE curves for 150 customers decrease in 0 segments. Enable the constraint.
Explicit credit model: lognormal income (median about 27 000 euros), uniform debt ratio in [0, 1], uniform age 20–70, with logit⁡P(devolver)=1.2log⁡(ingresos/27)−2(deuda−0.5)−((edad−45)/18)2+0.8\operatorname{logit} \Pr(\text{devolver}) = 1.2\log(\text{ingresos}/27) - 2(\text{deuda} - 0.5) - ((\text{edad} - 45)/18)^2 + 0.8: increasing in income and inverted-U in age. Two Newton logistic GBDTs (η=0.1\eta = 0.1, depth 3, λ=1\lambda = 1, 64 bins) train in your browser, unconstrained and increasing-constrained on the chosen feature using theorem bounds. The plot shows partial dependence (thick) and 10 ICE curves (thin) over 150 validation customers, true partial dependence (gray), and observed rate by decile. Readings give log-loss on 4000 validation customers.

Initially, without constraints, income partial dependence rises in irregular steps and falls in several sections, as do many individual ICE curves. Enabling the constraint eliminates falling sections: the curve becomes an increasing staircase and validation error barely changes or improves slightly because the constraint matches truth and regularizes. Now constrain age. Truth is an inverted U and the constraint forces the model to flatten after its maximum: validation error rises. A false constraint is bias no amount of data corrects.

Interaction constraints

Monotonic constraints control the shape of a feature’s effect; interaction constraints control which features can act together. In a tree, two features interact when they appear on the same root-to-leaf path: one’s effect depends on the other.

The consequence is a model decomposition you will prove in exercises: if each path uses features from one set, the model is a sum F(x)=∑S∈SFS(xS)F(\vb{x}) = \sum_{S \in \mathcal{S}} F_S(\vb{x}_S) where each summand depends only on one set’s features. With S={{1},…,{d}}\mathcal{S} = \{\{1\}, \dots, \{d\}\} each tree uses one feature and the GBDT is a generalized additive model (GAM): each feature’s complete effect can be drawn as a curve without averaging, giving interpretability by design. With pairs, the model has second-order interactions, each drawable as a map.

There are three uses. Interpretability: additive or allowed-pair models can be explained without approximation. Robustness: if a calendar feature’s effect should not depend on a store identifier, forbidding interaction prevents spurious patterns that fail under distribution shift. Regularization: fewer possible interactions means a smaller hypothesis space. The interactive credit model’s true logit is additive, and the lab cell uses this: additive restriction lowers validation error relative to the free model, and the income–age interaction invented by the free model disappears exactly.

DART: dropout for trees

Boosting adds trees correcting predecessors’ errors. Rashmi and Gilad-Bachrach (AISTATS 2015) identified a side effect called overspecialization: early trees capture almost all signal and late ones affect only a few rows, with negligible contributions elsewhere. In their figure 1, on CT slices regression, mean contribution of tree 100 in MART without shrinkage is about 15 orders of magnitude below the first; with shrinkage 0.10.1, “only” 4. The model becomes highly sensitive to early-tree decisions. Shrinkage mitigates but does not resolve it.

Normalization is subtle. Let D(x)=∑s∈Dwsfs(x)D(\vb{x}) = \sum_{s \in D} w_s f_s(\vb{x}) be the dropped contribution. Since the new tree fits what F^\hat F lacks, it learns approximately D(x)D(\vb{x}), kk times a typical dropped tree’s contribution. Simply adding it would yield F^+D+D\hat F + D + D: overshooting by counting the same thing twice. With normalization, if ft≈Df_t \approx D,

F^+kk+1D+1k+1ft≈F^+D=F,\hat F + \frac{k}{k + 1} D + \frac{1}{k + 1} f_t \approx \hat F + D = F,

prediction is preserved on average and the new tree has the same scale as each dropped tree after shrinkage (D/(k+1)D/(k + 1) versus Dk⋅kk+1\tfrac{D}{k}\cdot\tfrac{k}{k + 1}). XGBoost implements this normalization (normalize_type="tree", with learning rate in the denominator: 1/(k+η)1/(k + \eta)) and an alternative ("forest"); LightGBM with boosting="dart" defaults to drop_rate 0.1, skip_drop 0.5 (probability of skipping dropout in a round), and at most max_drop 50 trees.

Paper results are good but not universal. In ranking (MSLR-WEB10K), NDCG@3 46.7046.70 with DART versus 46.3146.31 with MART; in regression (CT slices, table 4), DART wins at all dataset sizes, e.g., L2 loss 27.9827.98 versus 29.2829.28 with 1000 trees (random forest 32.3332.33); in classification (face detection), MART wins 3 of 5 sizes, though best overall model is DART (0.97140.9714 accuracy versus 0.97070.9707). Training costs more: each round needs prediction without dropped trees, so accumulated predictions cannot be reused (XGBoost documentation states this), and early stopping is unstable because the model changes randomly; you also cannot truncate to an earlier tree count, because early weights were later rescaled. Prediction costs the same as MART with equal trees: nothing is dropped at prediction.

InteractiveDART versus MART
Mean contribution of each tree, Ex∣wtft(x)∣\mathbb{E}_x\lvert w_t f_t(x)\rvert (log scale)
Test mean squared error against the number of trees (noise contributes 1)
noise σ² = 1
  • MART, η=1\eta = 1
  • MART, η=0.1\eta = 0.1
  • DART, p=0.10p = 0.10
MART learning rate η\eta
0.10
Best test MSE, MART without shrinkage12.000 (1 trees)
Best test MSE, MART η = 0.112.000 (1 trees)
Best test MSE, DART12.000 (1 trees)
Contribution of tree 1 / tree 100MART 1×, DART 1.0×
DART (12.000) greatly improves on MART without shrinkage (12.000), but not MART with η = 0.1 (12.000). Its contribution profile is nearly flat.
Explicit Friedman 1 model: x∼Unif⁡[0,1]10\vb{x} \sim \Unif[0, 1]^{10} and y=10sin⁡(πx1x2)+20(x3−0.5)2+10x4+5x5+N(0,1)y = 10\sin(\pi x_1 x_2) + 20(x_3 - 0.5)^2 + 10x_4 + 5x_5 + \Normal(0, 1), with 500 training and 2000 test examples. Depth-3 Newton trees with λ=1\lambda = 1 and 32 bins train in your browser: MART without shrinkage (dashed gray), MART with selected rate (red) and DART with dropout probability pp (blue), 200 trees. Above, each tree's mean contribution to test prediction, Ex∣wtft(x)∣\E_x\abs{w_t f_t(\vb{x})}, on log scale (absolute value inside expectation, also mentioned by the paper); below, test mean squared error versus tree count, with noise floor.

The contribution profile matches the paper: MART without shrinkage falls about two orders of magnitude over 100 trees (183 times in the lab cell with another sample), MART with η=0.1\eta = 0.1 falls more slowly and DART is almost flat because dropout spreads signal across new trees. On test error, DART greatly improves on unshrunk MART but on this small problem does not beat MART with η=0.1\eta = 0.1: the lab cell agrees. This fits the paper’s mixed results and LightGBM’s guide, which lists “try DART” as an accuracy improvement, not default. DART merits a try when the model depends strongly on early trees or MART validation rises early even with small η\eta; if used, choose tree count with cross-validation instead of early stopping.

Weights, ranking and custom losses

All four libraries accept sample weights sample_weight. With weight viv_i, row loss is multiplied by viv_i, as are gradient and Hessian: gi→vigig_i \to v_i g_i, hi→vihih_i \to v_i h_i. Integer weight viv_i equals repeating the row viv_i times, and class weights (scale_pos_weight in XGBoost, class_weight in LightGBM and scikit-learn, auto_class_weights in CatBoost) assign equal weights to all rows in a class. Two consequences: Hessian minimums (min_child_weight, min_sum_hessian_in_leaf) measure total weight, not rows; and class reweighting changes model probabilities, which cease to be calibrated for the original distribution (if needed, recalibrate).

For ranking, the three main libraries provide objectives optimizing list metrics such as NDCG: rank:ndcg and rank:pairwise in XGBoost, lambdarank in LightGBM, YetiRank and others in CatBoost. Most descend from LambdaMART (Burges, 2010): gradients for document pairs within the same query multiplied by the list metric change if swapped. Data carry a query identifier (qid or group) and training/validation split is by query, not row.

You saw custom losses in the XGBoost lesson: provide gradient and Hessian with respect to margin. Remember two requirements: Hessian must be positive (or lower-bounded), because leaf weight −G/(H+λ)-G/(H + \lambda) ceases to be a minimum if H+λ≤0H + \lambda \le 0; and initial margin does not tune itself (XGBoost leaves 0.50.5 without base_score). An example is asymmetric squared loss, penalizing undershooting more than overshooting; its optimal constant prediction is not the mean but an expectile, which you will code in exercises.

Implementation from scratch

Cells in this section run in your browser. The first builds a minimal Newton logistic GBDT with quantile histograms (64 bins), depth-3 level-wise trees and λ=1\lambda = 1: the same algorithm inside the monotonicity interactive. Split search receives a function deciding child bounds so it can be changed. Start with the naive version, which only vetoes opposing local splits and passes parent bounds to children.

Monotonicity: local veto is insufficient

[ ]A constrained Newton GBDT and why local veto is insufficientBrowser
import numpy as np

def credito(n, semilla):
    """El modelo explícito del interactivo: ingresos (miles de euros), ratio de deuda y edad; y = 1 si devuelve."""
    r = np.random.default_rng(semilla)
    X = np.column_stack([np.exp(3.3 + 0.5 * r.normal(size=n)), r.uniform(size=n), r.uniform(20, 70, n)])
    z = 1.2 * np.log(X[:, 0] / 27) - 2 * (X[:, 1] - 0.5) - ((X[:, 2] - 45) / 18) ** 2 + 0.8
    return X, (r.uniform(size=n) < 1 / (1 + np.exp(-z))).astype(float), z

def cortes(X, B=64):
    """Umbrales por cuantiles: como mucho B - 1 por variable."""
    n = len(X)
    return [np.unique(np.sort(X[:, k])[np.minimum(n - 1, np.arange(1, B) * n // B)]) for k in range(X.shape[1])]

def discretizar(X, E):
    return np.column_stack([np.searchsorted(E[k], X[:, k], side="right") for k in range(X.shape[1])])

def obj(G, H, w, lam):
    return G * w + 0.5 * (H + lam) * w * w           # objetivo de Newton de una hoja de peso w

def cotas_heredadas(lo, hi, wl, wr, signo):
    return (lo, hi), (lo, hi)                          # ingenuo: los hijos heredan las cotas del padre

def arbol(Bn, E, g, h, prof, lam=1.0, min_h=1.0, mono=None, cotas=cotas_heredadas, inter=None):
    d = Bn.shape[1]
    mono = mono or [0] * d
    nodos = []                                         # [peso, variable, umbral, izquierdo, derecho]
    def crecer(ids, nivel, lo, hi, usadas):
        G, H = g[ids].sum(), h[ids].sum()
        w = float(np.clip(-G / (H + lam), lo, hi))     # el peso se recorta a las cotas del nodo
        yo = len(nodos)
        nodos.append([w, -1, 0.0, -1, -1])
        if nivel == prof:
            return yo
        permitidas = range(d) if inter is None else sorted({v for S in inter if usadas <= set(S) for v in S})
        mejor = None
        for f in permitidas:
            nb = len(E[f]) + 1
            GL = np.cumsum(np.bincount(Bn[ids, f], g[ids], nb))[:-1]
            HL = np.cumsum(np.bincount(Bn[ids, f], h[ids], nb))[:-1]
            wl = np.clip(-GL / (HL + lam), lo, hi)
            wr = np.clip(-(G - GL) / (H - HL + lam), lo, hi)
            gan = obj(G, H, w, lam) - obj(GL, HL, wl, lam) - obj(G - GL, H - HL, wr, lam)
            ok = (HL >= min_h) & (H - HL >= min_h) & (gan > 1e-12)
            if mono[f] > 0:
                ok &= wl <= wr                         # el veto local
            elif mono[f] < 0:
                ok &= wl >= wr
            if ok.any():
                j = int(np.argmax(np.where(ok, gan, -np.inf)))
                if mejor is None or gan[j] > mejor[0]:
                    mejor = (gan[j], f, j, wl[j], wr[j])
        if mejor is None:
            return yo
        _, f, j, wl, wr = mejor
        (a, b), (c, e) = cotas(lo, hi, wl, wr, mono[f])
        izq = Bn[ids, f] <= j                          # contenedor <= j  <=>  x < umbral j
        nodos[yo][1:3] = [f, E[f][j]]
        nodos[yo][3] = crecer(ids[izq], nivel + 1, a, b, usadas | {f})
        nodos[yo][4] = crecer(ids[~izq], nivel + 1, c, e, usadas | {f})
        return yo
    crecer(np.arange(len(g)), 0, -np.inf, np.inf, frozenset())
    return nodos

def evaluar(nodos, X):
    out, pila = np.empty(len(X)), [(0, np.arange(len(X)))]
    while pila:
        k, ids = pila.pop()
        w, f, t, l, r = nodos[k]
        if f < 0:
            out[ids] = w
        else:
            m = X[ids, f] < t
            pila += [(l, ids[m]), (r, ids[~m])]
    return out

def gbdt(X, y, T=150, eta=0.1, prof=3, **kw):
    """Boosting logístico de Newton; devuelve la función que da el margen F(x)."""
    E = cortes(X)
    Bn = discretizar(X, E)
    F0 = np.log(y.mean() / (1 - y.mean()))
    F, arboles = np.full(len(y), F0), []
    for _ in range(T):
        p = 1 / (1 + np.exp(-F))
        arboles.append(arbol(Bn, E, p - y, p * (1 - p), prof, **kw))
        F += eta * evaluar(arboles[-1], X)
    return lambda Z: F0 + eta * sum(evaluar(a, Z) for a in arboles)

def logloss(y, F):
    return float(np.mean(np.logaddexp(0, F) - y * F))

def tramos_que_bajan(modelo, filas, k, malla):
    """Recorre la malla en la variable k para cada fila (curvas ICE) y cuenta los tramos en que el margen baja."""
    Z = np.repeat(filas, len(malla), axis=0)
    Z[:, k] = np.tile(malla, len(filas))
    M = modelo(Z).reshape(len(filas), len(malla))
    return int((np.diff(M, axis=1) < -1e-12).sum())

Xtr, ytr, _ = credito(1000, 1)
Xva, yva, zva = credito(4000, 2)
malla = np.exp(np.linspace(np.log(9), np.log(85), 100))      # ingresos de 9 000 a 85 000 euros
filas = Xva[:200]
print(f"log-loss de validación del modelo verdadero: {logloss(yva, zva):.4f}")
libre = gbdt(Xtr, ytr)
veto = gbdt(Xtr, ytr, mono=[1, 0, 0])
for nombre, m in [("sin restricción", libre), ("solo el veto local", veto)]:
    print(f"{nombre:19s} validación {logloss(yva, m(Xva)):.4f}   tramos de ingresos que bajan: {tramos_que_bajan(m, filas, 0, malla)} de {200 * 99}")

The unconstrained model decreases in 1852 of 19 800 intervals across 200 ICE curves, nearly one in ten: with 1000 customers noise produces jaggedness everywhere. Local veto reduces this to 205, not zero; the text’s measured counterexample. Also note log-loss scale: 0.62820.6282 and 0.62700.6270 versus the true model’s 0.59380.5938, the lower bound on these data. The gap is variance: little data for what the model can learn.

Midpoint bounds and comparison with scikit-learn

The theorem’s fix: on a constrained-feature split, left receives [ℓ,m][\ell, m] and right [m,u][m, u] with mm the midpoint of the two weights. The cell implements only the increasing case (general is an exercise) and compares with HistGradientBoostingClassifier(monotonic_cst=...), configured as similarly as possible: depth 3, 8 leaves, λ=1\lambda = 1 and 64 bins.

[ ]Midpoint bounds, monotonic_cst and interaction constraintsBrowser
from sklearn.ensemble import HistGradientBoostingClassifier

def cotas_creciente(lo, hi, wl, wr, signo):
    assert signo >= 0, "esta versión solo cubre las restricciones crecientes"
    if signo == 0:
        return (lo, hi), (lo, hi)
    m = 0.5 * (wl + wr)
    return (lo, m), (m, hi)

propio = gbdt(Xtr, ytr, mono=[1, 0, 0], cotas=cotas_creciente)
P = dict(learning_rate=0.1, max_iter=150, max_depth=3, max_leaf_nodes=8, min_samples_leaf=1, l2_regularization=1.0,
         max_bins=64, early_stopping=False, random_state=0)
hgb_libre = HistGradientBoostingClassifier(**P).fit(Xtr, ytr)
hgb_mono = HistGradientBoostingClassifier(monotonic_cst=[1, 0, 0], **P).fit(Xtr, ytr)
margen = lambda m: m.decision_function
for nombre, f in [("propio, punto medio", propio), ("HistGB sin restricción", margen(hgb_libre)), ("HistGB monotonic_cst", margen(hgb_mono))]:
    print(f"{nombre:23s} validación {logloss(yva, f(Xva)):.4f}   tramos que bajan: {tramos_que_bajan(f, filas, 0, malla)}")

def interaccion_max(f, filas, ing=(15, 60), edad=(30, 60)):
    """max |F(i1,e1) - F(i1,e0) - F(i0,e1) + F(i0,e0)|: es 0 si F no tiene interacción entre ingresos y edad."""
    Z = np.repeat(filas, 4, axis=0)
    Z[:, 0] = np.tile([ing[0], ing[1], ing[0], ing[1]], len(filas))
    Z[:, 2] = np.tile([edad[0], edad[0], edad[1], edad[1]], len(filas))
    F = f(Z).reshape(-1, 4)
    return float(np.abs(F[:, 3] - F[:, 2] - F[:, 1] + F[:, 0]).max())

print()
hgb_aditivo = HistGradientBoostingClassifier(interaction_cst=[[0], [1], [2]], **P).fit(Xtr, ytr)
for nombre, f in [("libre", libre), ("[[0, 1], [2]]", gbdt(Xtr, ytr, inter=[[0, 1], [2]])),
                  ("aditivo [[0], [1], [2]]", gbdt(Xtr, ytr, inter=[[0], [1], [2]])), ("HistGB aditivo", margen(hgb_aditivo))]:
    print(f"{nombre:23s} validación {logloss(yva, f(Xva)):.4f}   interacción ingresos-edad: {interaccion_max(f, filas[:50]):.1e}")

With midpoint bounds none of 19 800 intervals decreases, and validation log-loss improves to 0.62580.6258: the true constraint removes variance. Unconstrained HistGradientBoostingClassifier decreases in 2127 intervals and with monotonic_cst none, with the same log-loss in each case (0.63300.6330 and 0.63370.6337); it differs from ours because it is a different algorithm (leaf-wise growth and its own discretization), but uses the same bounds rule.

The second part measures income–age interaction via mixed difference F(i1,e1)−F(i1,e0)−F(i0,e1)+F(i0,e0)F(i_1, e_1) - F(i_1, e_0) - F(i_0, e_1) + F(i_0, e_0), zero if and only if the income effect does not depend on age between those values. The free model reaches 0.880.88 in margin for some customer: it invented an interaction absent from the additive true logit. With constraint [[0,1],[2]][[0, 1], [2]] separating age from the other two, or the additive constraint, mixed difference is on the order of 10−1510^{-15}, rounding error, as the decomposition theorem predicts; validation improves to 0.61720.6172 and 0.62270.6227. HistGB with additive interaction_cst gives 0.62240.6224. Both constraints are true in this model and thus help; their difference comes from one sample and should not be overinterpreted.

DART from scratch

The third cell implements Rashmi and Gilad-Bachrach algorithm 1 with squared loss on the interactive’s Friedman 1, reusing the first cell’s Newton trees (with Hessian 1 they are least-squares trees). To avoid recomputing the full model each round it stores each tree’s unweighted prediction and combines rows by matrix product.

[ ]DART versus MARTBrowser
def friedman(n, semilla):
    r = np.random.default_rng(semilla)
    X = r.uniform(size=(n, 10))
    y = 10 * np.sin(np.pi * X[:, 0] * X[:, 1]) + 20 * (X[:, 2] - 0.5) ** 2 + 10 * X[:, 3] + 5 * X[:, 4] + r.normal(size=n)
    return X, y

def boosting(X, y, Xp, yp, T=150, p=0.0, eta=1.0, semilla=0, prof=3):
    """p = 0: MART con tasa eta. p > 0: DART (algoritmo 1 del artículo, sin tasa)."""
    r = np.random.default_rng(semilla)
    E = cortes(X, 32)
    Bn = discretizar(X, E)
    P, Pp = np.zeros((T, len(y))), np.zeros((T, len(yp)))   # predicción de cada árbol sin su peso
    w, ecm = np.zeros(T), []
    for t in range(T):
        caidos = np.zeros(t, bool)
        if p > 0 and t > 0:
            caidos = r.uniform(size=t) < p
            if not caidos.any():
                caidos[r.integers(t)] = True               # «binomial más uno»: al menos un árbol fuera
        F = y.mean() + w[:t][~caidos] @ P[:t][~caidos]     # el modelo sin los descartados
        nodos = arbol(Bn, E, F - y, np.ones(len(y)), prof)
        P[t], Pp[t] = evaluar(nodos, X), evaluar(nodos, Xp)
        k = caidos.sum()
        if p > 0:
            w[:t][caidos] *= k / (k + 1)                   # los k descartados se encogen
            w[t] = 1.0 if t == 0 else 1 / (k + 1)          # y el nuevo entra con el peso de cada uno
        else:
            w[t] = eta
        ecm.append(np.mean((yp - y.mean() - w[:t + 1] @ Pp[:t + 1]) ** 2))
    contrib = np.abs(w[:, None] * Pp).mean(axis=1)          # E_x |w_t f_t(x)| en los datos de prueba
    return np.array(ecm), contrib

def informe(nombre, e, c):
    print(f"{nombre:16s} mejor ECM de prueba {e.min():.3f} ({e.argmin() + 1:3d} árboles), con 150: {e[-1]:.3f};"
          f"  contribución del árbol 1 / la del 100: {c[0] / c[99]:.3g}")

X, y = friedman(500, 11)
Xp, yp = friedman(2000, 12)
for nombre, kw in [("MART, eta = 1", dict(eta=1.0)), ("MART, eta = 0.1", dict(eta=0.1))]:
    informe(nombre, *boosting(X, y, Xp, yp, **kw))

Now DART with the same function and dropout probability p=0.1p = 0.1:

[ ]DART with p = 0.1Browser
informe("DART, p = 0.1", *boosting(X, y, Xp, yp, p=0.1))

All three contribution profiles match the paper. In MART without shrinkage the first tree contributes 183 times the 100th, and best test error (5.4415.441) arrives with only 6 trees: later trees specialize in a few rows and worsen test. With η=0.1\eta = 0.1 the ratio drops to 29.629.6 and error to 2.2382.238, still improving at 146 trees. With DART the ratio is 0.7830.783: the first tree ultimately contributes less than the hundredth, because every dropout multiplies its weight by k/(k+1)k/(k + 1). The profile is flat, as promised.

DART’s best test error 2.6792.679 greatly improves on MART without shrinkage, but not MART with η=0.1\eta = 0.1. Its best arrives at 39 trees; at 150 it rises to 2.9692.969: DART also overfits, and because its model changes randomly when adding trees, its test curve is less useful for stopping than MART’s. On these 500 rows, shrinkage remedies overspecialization better than dropout; in the interactive change pp and MART’s rate to see how much the conclusion depends on them.

Learning rate and tree count

The final browser cell checks heuristic T∗≈s∗/ηT^* \approx s^*/\eta with scikit-learn’s GradientBoostingRegressor (depth-3 trees) on Friedman 1: train at four rates to the same “time” ηt=8\eta t = 8 and compare training error at matching times, and trees needed by each rate to fall below validation error 2.82.8.

[ ]With small eta the model depends on eta·tBrowser
from sklearn.datasets import make_friedman1
from sklearn.ensemble import GradientBoostingRegressor

X, y = make_friedman1(1600, noise=1.0, random_state=0)
Xtr, ytr, Xva, yva = X[:600], y[:600], X[600:], y[600:]
print("  eta  árboles   ECM de entrenamiento con eta·t = 1, 2, 4, 8    árboles hasta ECM de validación < 2.8   eta·t")
for eta in (0.4, 0.1, 0.05, 0.025):
    T = int(round(8 / eta))
    m = GradientBoostingRegressor(learning_rate=eta, n_estimators=T, max_depth=3, random_state=0).fit(Xtr, ytr)
    tr = np.array([np.mean((ytr - p) ** 2) for p in m.staged_predict(Xtr)])
    va = np.array([np.mean((yva - p) ** 2) for p in m.staged_predict(Xva)])
    t_u = int(np.argmax(va < 2.8)) + 1 if (va < 2.8).any() else None
    print(f"{eta:5.3f} {T:6d}     " + "  ".join(f"{tr[int(round(s / eta)) - 1]:6.3f}" for s in (1, 2, 4, 8))
          + (f"                {t_u:5d}                        {eta * t_u:5.2f}" if t_u else "                no llega"))

With η=0.1\eta = 0.1, 0.050.05 and 0.0250.025, training error at the same time ηt\eta t is nearly equal (at ηt=8\eta t = 8: 0.8240.824, 0.8320.832 and 0.8610.861), although tree count ranges from 80 to 320; with η=0.4\eta = 0.4 the path differs (1.1461.146 at ηt=8\eta t = 8), and 20 trees never reach the validation threshold. Trees needed to reach validation error 2.82.8 scale as 1/η1/\eta: 69, 133 and 267, with ηt\eta t between 6.656.65 and 6.906.90. Halving η\eta doubles trees; this is the rate exercise’s rule.

A fair benchmark on your machine

Library comparisons are easy to do badly. A fair benchmark needs four things: the same protocol for all (splits, metric, tree-count selection), the same tuning budget (trial count and equivalent search spaces), evaluation data unused in any choice (nested CV), and several seeds with interval, since differences between well-tuned libraries are often on the order of noise. It is also a software experiment, so it needs fixed versions (a locked dependency environment) and explicit seeding strategy.

The next cell runs locally with real libraries. It compares four libraries on three OpenML datasets chosen to stress different design choices: credit-g (1000 rows, 13 low-cardinality categoricals: small), Amazon Employee Access (32 769 rows, 9 categoricals with up to 7518 levels: categorical), and Higgs (98 050 rows, 28 numeric: large). Protocol:

  • Outer CV: 3 stratified folds, repeated with 5 seeds. Each test fold is used only for measurement.
  • Inner tuning: within each training fold, 20% holdout for early stopping and trial selection; 30 Optuna (TPE) trials per library and fold with equivalent spaces (rate, complexity, minimum leaf, rows, columns, λ\lambda). Without Optuna the cell uses equal-budget random search; install with python -m pip install optuna.
  • Retraining: with chosen hyperparameters and the entire training fold, tree count from early stopping scaled by 1/0.81/0.8 (25% more data).
  • Categoricals: native in XGBoost (enable_categorical), LightGBM and CatBoost; in HistGB, which allows at most 255 levels, higher-cardinality features pass through scikit-learn TargetEncoder, using cross-fitting to avoid label leakage.
  • Reporting: outer-test log-loss and AUC, tt 95% interval between the 5 seed means, inner-validation optimism, library defaults on the same folds, and CPU/GPU times with fixed parameters.

The full benchmark takes hours: let it run. A short version verified the cell (environment variable ORYON_VERIFY_SHORT=1: 4 trials, 2 folds, one seed and Higgs reduced to 20 000 rows in comparison; timings use full Higgs), and the numbers discussed are from that run; so few trials verify code works, not a result.

[ ]GBDT benchmark: four libraries, three datasets, nested CVLocal GPU
import os, time, json, warnings, tempfile
import numpy as np
import pandas as pd
import xgboost as xgb
import lightgbm as lgb
import catboost as cb
from scipy import stats
from sklearn.datasets import fetch_openml
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import log_loss, roc_auc_score
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.preprocessing import TargetEncoder
warnings.filterwarnings("ignore")
try:
    import optuna
    optuna.logging.set_verbosity(optuna.logging.WARNING)
except ImportError:                                  # python -m pip install optuna
    optuna = None

CORTO = os.environ.get("ORYON_VERIFY_SHORT") == "1"  # ejecución corta de verificación
ENSAYOS, PLIEGUES, SEMILLAS, RONDAS = (4, 2, 1, 600) if CORTO else (30, 3, 5, 5000)
HILOS = 4 if CORTO else os.cpu_count()
print("versiones:", "xgboost", xgb.__version__, "| lightgbm", lgb.__version__, "| catboost", cb.__version__,
      "| optuna", optuna.__version__ if optuna else "no instalado: búsqueda aleatoria con el mismo presupuesto")
print(f"presupuesto: {ENSAYOS} ensayos por librería y pliegue, {PLIEGUES} pliegues externos x {SEMILLAS} semillas" + (" (CORTO)" if CORTO else ""))

def cargar(data_id, n_max=None):
    d = fetch_openml(data_id=data_id, as_frame=True, parser="liac-arff")
    X, y = d.data.copy(), d.target.astype(str)
    y = (y == sorted(y.unique())[-1]).astype(int).to_numpy()   # clase positiva: la última en orden alfabético
    for c in X.columns:
        if data_id == 4135 or not pd.api.types.is_numeric_dtype(X[c]):
            X[c] = X[c].astype(str).astype("category")
        else:
            X[c] = X[c].astype(float)
    if n_max and len(y) > n_max:
        idx = np.random.default_rng(0).choice(len(y), n_max, replace=False)
        X, y = X.iloc[idx].reset_index(drop=True), y[idx]
    return X, y

DATOS = {"credit-g (pequeño)": cargar(31), "Amazon (categóricas)": cargar(4135), "Higgs (grande)": cargar(23512, 20000 if CORTO else None)}
for k, (X, y) in DATOS.items():
    cats = [c for c in X if str(X[c].dtype) == "category"]
    print(f"{k:22s} filas {len(y):6d}  variables {X.shape[1]:3d}  categóricas {len(cats):2d}"
          f"  niveles máx {max([X[c].nunique() for c in cats], default=0):5d}  fracción y=1 {y.mean():.3f}")

# --- espacios de búsqueda: el mismo tipo de mando en las cuatro librerías ------------------------------
def espacio(lib, t):
    p = {"lr": t.suggest_float("lr", 0.01, 0.3, log=True), "fil": t.suggest_float("fil", 0.5, 1.0),
         "l2": t.suggest_float("l2", 1e-3, 100, log=True)}
    if lib == "XGBoost":
        p |= {"max_depth": t.suggest_int("max_depth", 2, 10), "min_child_weight": t.suggest_float("mcw", 0.1, 100, log=True),
              "col": t.suggest_float("col", 0.5, 1.0)}
    elif lib == "LightGBM":
        p |= {"num_leaves": t.suggest_int("num_leaves", 4, 256, log=True), "min_data_in_leaf": t.suggest_int("mdl", 2, 200, log=True),
              "col": t.suggest_float("col", 0.5, 1.0)}
    elif lib == "CatBoost":
        p |= {"depth": t.suggest_int("depth", 3, 10), "col": t.suggest_float("col", 0.5, 1.0)}
    else:
        p |= {"max_leaf_nodes": t.suggest_int("max_leaf_nodes", 4, 256, log=True), "min_samples_leaf": t.suggest_int("msl", 2, 200, log=True),
              "col": t.suggest_float("col", 0.5, 1.0)}
    return p

class EnsayoAleatorio:                                # la misma interfaz que optuna.Trial, con muestreo uniforme
    def __init__(self, rng):
        self.r, self.user_attrs, self.valores = rng, {}, {}
    def set_user_attr(self, k, v):
        self.user_attrs[k] = v
    def suggest_float(self, n, a, b, log=False):
        v = float(np.exp(self.r.uniform(np.log(a), np.log(b)))) if log else float(self.r.uniform(a, b))
        self.valores[n] = v
        return v
    def suggest_int(self, n, a, b, log=False):
        v = int(round(float(np.exp(self.r.uniform(np.log(a), np.log(b)))) if log else float(self.r.uniform(a, b))))
        self.valores[n] = v
        return v

class optuna_fijo:                                    # devuelve valores ya elegidos (como optuna.trial.FixedTrial)
    def __init__(self, v): self.v = v
    def suggest_float(self, n, *a, **k): return self.v[n]
    def suggest_int(self, n, *a, **k): return self.v[n]

def preparar_hgb(Xa, ya, otros, semilla):
    """HistGB admite como mucho 255 niveles por categórica: las de más niveles van con TargetEncoder (cross-fitting)."""
    altas = [c for c in Xa if str(Xa[c].dtype) == "category" and Xa[c].nunique() > 250]
    if not altas:
        return Xa, otros
    te = TargetEncoder(target_type="binary", random_state=semilla)
    A = Xa.copy()
    A[altas] = te.fit_transform(Xa[altas].astype(str), ya)             # cross-fitting: sin fuga en entrenamiento
    out = []
    for O in otros:
        B = O.copy()
        B[altas] = te.transform(O[altas].astype(str))
        out.append(B)
    return A, out

def entrenar(lib, p, Xf, yf, Xv, yv, semilla, rondas=RONDAS, dispositivo="cpu", parada=True):
    """Entrena con parada temprana sobre (Xv, yv); devuelve el modelo, el número de árboles y una función de predicción."""
    cats = [c for c in Xf if str(Xf[c].dtype) == "category"]
    if lib == "XGBoost":
        m = xgb.XGBClassifier(n_estimators=rondas, learning_rate=p["lr"], max_depth=p["max_depth"], min_child_weight=p["min_child_weight"],
                              subsample=p["fil"], colsample_bytree=p["col"], reg_lambda=p["l2"], tree_method="hist",
                              enable_categorical=True, max_cat_to_onehot=1, early_stopping_rounds=50 if parada else None,
                              n_jobs=HILOS, random_state=semilla, device=dispositivo, eval_metric="logloss")
        m.fit(Xf, yf, eval_set=[(Xv, yv)], verbose=False)
        n = m.best_iteration + 1 if parada else rondas
        return n, lambda Z: m.predict_proba(Z, iteration_range=(0, n))[:, 1]
    if lib == "LightGBM":
        m = lgb.LGBMClassifier(n_estimators=rondas, learning_rate=p["lr"], num_leaves=p["num_leaves"], min_child_samples=p["min_data_in_leaf"],
                               subsample=p["fil"], subsample_freq=1, colsample_bytree=p["col"], reg_lambda=p["l2"],
                               n_jobs=HILOS, random_state=semilla, verbose=-1, device_type=dispositivo)
        m.fit(Xf, yf, eval_set=[(Xv, yv)], callbacks=[lgb.early_stopping(50, verbose=False)] if parada else [])
        n = m.best_iteration_ if parada and m.best_iteration_ else rondas
        return n, lambda Z: m.predict_proba(Z, num_iteration=n)[:, 1]
    if lib == "CatBoost":
        gpu = dispositivo != "cpu"
        m = cb.CatBoostClassifier(iterations=rondas, learning_rate=p["lr"], depth=p["depth"], l2_leaf_reg=p["l2"],
                                  bootstrap_type="Bernoulli", subsample=p["fil"], rsm=None if gpu else p["col"],
                                  od_type="Iter" if parada else None, od_wait=50 if parada else None, use_best_model=parada,
                                  random_seed=semilla, thread_count=HILOS, verbose=0, task_type="GPU" if gpu else "CPU",
                                  allow_writing_files=False, train_dir=tempfile.gettempdir())
        m.fit(Xf, yf, cat_features=cats, eval_set=(Xv, yv))
        n = m.get_best_iteration() + 1 if parada else rondas
        return n, lambda Z: m.predict_proba(Z)[:, 1]
    Xf2, (Xv2,) = preparar_hgb(Xf, yf, [Xv], semilla)
    m = HistGradientBoostingClassifier(learning_rate=p["lr"], max_iter=rondas, max_leaf_nodes=p["max_leaf_nodes"],
                                       min_samples_leaf=p["min_samples_leaf"], l2_regularization=p["l2"], max_features=p["col"],
                                       categorical_features="from_dtype", early_stopping=False, random_state=semilla)
    m.fit(Xf2, yf)
    perd = [log_loss(yv, q[:, 1]) for q in m.staged_predict_proba(Xv2)] if parada else None
    n = int(np.argmin(perd)) + 1 if parada else rondas
    # HistGB no tiene parada con un conjunto externo: se entrena hasta el máximo y se corta en la mejor iteración
    def pred(Z):
        _, (Z2,) = preparar_hgb(Xf, yf, [Z], semilla)
        for i, q in enumerate(m.staged_predict_proba(Z2), 1):
            if i == n:
                return q[:, 1]
    return n, pred

def ajustar(lib, Xa, ya, semilla):
    """Validación interna por retención: 80 % para entrenar, 20 % para la parada temprana y para elegir el ensayo."""
    Xf, Xv, yf, yv = train_test_split(Xa, ya, test_size=0.2, random_state=semilla, stratify=ya)
    def objetivo(t):
        p = espacio(lib, t)
        n, pred = entrenar(lib, p, Xf, yf, Xv, yv, semilla)
        t.set_user_attr("n", n)
        return log_loss(yv, pred(Xv))
    if optuna:
        est = optuna.create_study(direction="minimize", sampler=optuna.samplers.TPESampler(seed=semilla))
        est.optimize(objetivo, n_trials=ENSAYOS)
        mejor = est.best_trial
        return espacio(lib, optuna.trial.FixedTrial(mejor.params)), mejor.user_attrs["n"], mejor.value
    r, res = np.random.default_rng(semilla), []
    for _ in range(ENSAYOS):
        t = EnsayoAleatorio(r)
        v = objetivo(t)
        res.append((v, espacio(lib, optuna_fijo(t.valores)), t.user_attrs["n"]))
    v, p, n = min(res, key=lambda z: z[0])
    return p, n, v

LIBS = ["XGBoost", "LightGBM", "CatBoost", "HistGB"]
filas = []
for nombre, (X, y) in DATOS.items():
    for s in range(SEMILLAS):
        for k, (itr, ite) in enumerate(StratifiedKFold(PLIEGUES, shuffle=True, random_state=s).split(X, y)):
            Xa, Xt, ya, yt = X.iloc[itr], X.iloc[ite], y[itr], y[ite]
            for lib in LIBS:
                t0 = time.perf_counter()
                p, n, vint = ajustar(lib, Xa, ya, s)
                t_aj = time.perf_counter() - t0
                # reentrenar con todo el pliegue de entrenamiento, con los árboles de la parada escalados por 1/0.8
                nf = max(1, int(round(n / 0.8)))
                t0 = time.perf_counter()
                _, pred = entrenar(lib, p, Xa, ya, Xa.iloc[:1], ya[:1], s, rondas=nf, parada=False)
                t_fin = time.perf_counter() - t0
                q = np.clip(pred(Xt), 1e-7, 1 - 1e-7)
                filas.append(dict(datos=nombre, lib=lib, semilla=s, pliegue=k, logloss=log_loss(yt, q), auc=roc_auc_score(yt, q),
                                  interna=vint, arboles=nf, seg_ajuste=t_aj, seg_final=t_fin))
            print(f"{nombre:22s} semilla {s} pliegue {k}: " + "  ".join(f"{f['lib']} {f['logloss']:.4f}" for f in filas[-4:]), flush=True)

R = pd.DataFrame(filas)
def intervalo(v):
    v = np.asarray(v)
    if len(v) < 2:
        return f"{v.mean():.4f}"
    h = stats.t.ppf(0.975, len(v) - 1) * v.std(ddof=1) / np.sqrt(len(v))
    return f"{v.mean():.4f} ± {h:.4f}"
print("\nlog-loss de prueba externa (media de cada semilla sobre sus pliegues; intervalo t al 95 % entre semillas)")
por_semilla = R.groupby(["datos", "lib", "semilla"])[["logloss", "auc", "interna", "arboles", "seg_ajuste"]].mean().reset_index()
for nombre in DATOS:
    for lib in LIBS:
        r = por_semilla[(por_semilla.datos == nombre) & (por_semilla.lib == lib)]
        print(f"{nombre:22s} {lib:9s} log-loss {intervalo(r.logloss):18s} AUC {r.auc.mean():.4f}  interna {r.interna.mean():.4f}"
              f"  árboles {r.arboles.mean():6.0f}  ajuste {r.seg_ajuste.mean():6.1f} s")
print("\noptimismo de la validación interna (interna − externa, media):",
      {lib: round(float((R[R.lib == lib].interna - R[R.lib == lib].logloss).mean()), 4) for lib in LIBS})

# --- valores por defecto, sin ajuste ni parada temprana, con el mismo protocolo externo ------------------------
print("\nvalores por defecto de cada librería (mismos pliegues externos, semilla 0)")
for nombre, (X, y) in DATOS.items():
    out = []
    for itr, ite in StratifiedKFold(PLIEGUES, shuffle=True, random_state=0).split(X, y):
        Xa, Xt, ya, yt = X.iloc[itr], X.iloc[ite], y[itr], y[ite]
        cats = [c for c in Xa if str(Xa[c].dtype) == "category"]
        mods = {"XGBoost": xgb.XGBClassifier(enable_categorical=True, n_jobs=HILOS, random_state=0).fit(Xa, ya),
                "LightGBM": lgb.LGBMClassifier(n_jobs=HILOS, random_state=0, verbose=-1).fit(Xa, ya),
                "CatBoost": cb.CatBoostClassifier(verbose=0, random_seed=0, thread_count=HILOS, allow_writing_files=False).fit(Xa, ya, cat_features=cats)}
        Xa2, (Xt2,) = preparar_hgb(Xa, ya, [Xt], 0)
        mods["HistGB"] = HistGradientBoostingClassifier(categorical_features="from_dtype", random_state=0).fit(Xa2, ya)
        out.append({k: log_loss(yt, np.clip(m.predict_proba(Xt2 if k == "HistGB" else Xt)[:, 1], 1e-7, 1 - 1e-7)) for k, m in mods.items()})
    print(f"{nombre:22s} " + "  ".join(f"{k} {np.mean([o[k] for o in out]):.4f}" for k in LIBS))

# --- tiempos en CPU y en GPU con parámetros fijos: 300 árboles de unas 64 hojas en Higgs ----------------------
X, y = cargar(23512)                                  # Higgs entero, también en la ejecución corta
Xf, Xv, yf, yv = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
fijos = {"XGBoost": {"lr": 0.1, "fil": 1.0, "l2": 1.0, "max_depth": 6, "min_child_weight": 1.0, "col": 1.0},
         "LightGBM": {"lr": 0.1, "fil": 1.0, "l2": 1.0, "num_leaves": 64, "min_data_in_leaf": 20, "col": 1.0},
         "CatBoost": {"lr": 0.1, "fil": 1.0, "l2": 1.0, "depth": 6, "col": 1.0},
         "HistGB": {"lr": 0.1, "fil": 1.0, "l2": 1.0, "max_leaf_nodes": 64, "min_samples_leaf": 20, "col": 1.0}}
tiempos = []
print(f"\ntiempo de entrenar 300 árboles con {len(yf)} filas de Higgs ({HILOS} hilos de CPU)")
for lib in LIBS:
    fila = {"lib": lib}
    for disp in ["cpu", "cuda"]:
        if lib == "HistGB" and disp == "cuda":
            fila["gpu"] = None
            continue
        try:
            entrenar(lib, fijos[lib], Xf.iloc[:2000], yf[:2000], Xv, yv, 0, rondas=10, dispositivo=disp, parada=False)   # calentamiento
            t0 = time.perf_counter()
            _, pred = entrenar(lib, fijos[lib], Xf, yf, Xv, yv, 0, rondas=300, dispositivo=disp, parada=False)
            fila["gpu" if disp == "cuda" else "cpu"] = round(time.perf_counter() - t0, 2)
            print(f"  {lib:9s} {disp:4s} {time.perf_counter() - t0:6.2f} s   log-loss de validación {log_loss(yv, pred(Xv)):.4f}")
        except Exception as e:
            fila["gpu"] = None
            print(f"  {lib:9s} {disp:4s} no disponible: {str(e).splitlines()[0][:90]}")
    tiempos.append(fila)
print(json.dumps({"rows": len(yf), "trees": 300, "threads": HILOS, "times": tiempos}, ensure_ascii=False))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The short-run verification Python lacked Optuna, so tuning used 4 random trials, 2 folds and one seed: no intervals, and no small difference means anything. Still, four observations emerge for the full benchmark to confirm, explained by earlier lessons.

Amazon separates CatBoost. Its test log-loss is 0.15150.1515 (AUC 0.86550.8655), versus 0.16780.1678 to 0.17350.1735 for the others (AUC around 0.820.82). This is the high-cardinality dataset where CatBoost’s ordered statistics and categorical combinations exploit information gradient partitioning overfits, as seen previously. On all-numeric Higgs the four lie between 0.56010.5601 and 0.56490.5649: without categoricals, designs converge.

Defaults can be disastrous or excellent. Default XGBoost gives 0.62970.6297 on credit-g (tuned 0.48480.4848) and 0.33800.3380 on Amazon, twice tuned (0.16780.1678): η=0.3\eta = 0.3 and depth 6 with 500 training rows, or thousands-level categoricals split by gradient, overfit unchecked. Default CatBoost gives 0.48810.4881 on credit-g, better than its “tuned” version (0.52130.5213), and the same 0.15150.1515 on Amazon. CatBoost defaults (symmetric trees, 1000 iterations with data-chosen rate) are famous for working well untouched, reflected here.

Very-low-budget tuning can be worse than no tuning. On Higgs, LightGBM, CatBoost and HistGB defaults (0.55930.5593, 0.55640.5564 and 0.55890.5589) beat their 4-random-trial versions. With so few trials none may land in a good region. This is why the full lab uses 30 and why defaults should be the first trial of any search (Optuna study.enqueue_trial).

GPU helps, but not at this scale. With Higgs’s 78 440 training rows and 300 trees, GPU speeds XGBoost by factor 1.71.7 and CatBoost by 22, while pip LightGBM has no CUDA support (it must be compiled). These are once-measured times on a shared machine: treat as order-of-magnitude. At this size tuning cost is dominated by trial count and library (CatBoost and HistGB are slowest per trial in the table), not device.

When running the full version, look for three things: whether four-library intervals overlap on Higgs and credit-g (expected), whether CatBoost’s Amazon advantage persists with 30 trials, and how optimistic inner validation is relative to outer test.

Common mistakes

Exercises

Quiz255 leaves with 5000 rows
You have 5000 rows and 30 numeric features, and train LightGBM with num_leaves = 255 and min_data_in_leaf = 1, η=0.1\eta = 0.1 and early stopping. What is the main risk?
QuizHigh-cardinality categoricals without leakage
You have 5000 merchant identifiers and want to pass the feature as-is without preprocessing, with explicit protection against label leakage. Which library does this by design?
NumericLowering the rate
With η=0.1\eta = 0.1, early stopping chose 400 trees. You lower rate to η=0.02\eta = 0.02 without changing anything else. Approximately how many trees should early stopping now choose?
Numericmin_child_weight in rows
XGBoost with logistic loss and min_child_weight = 1 (default). In a region where the current model predicts p=0.95p = 0.95 for every row, how many rows must a leaf have at minimum for the split to be valid?
QuizWhy vetoing a split is insufficient
A depth-2 tree constrained increasing in income splits the root by income with weights wL=−0.2<wR=0.1w_L = -0.2 < w_R = 0.1, then each child splits by age. Only local splits with wL>wRw_L > w_R on the constrained feature are vetoed. What can go wrong?
CodeChild bounds for either sign
Write cotas_hijos(lo, hi, wl, wr, signo), receiving node interval [lo,hi][\texttt{lo}, \texttt{hi}], clipped weights of both children of the chosen split, and constraint sign for the split feature (1 increasing, -1 decreasing, 0 free), and returning ((lo_izq, hi_izq), (lo_der, hi_der)), the two child intervals (left contains smaller feature values). Tests use it in a least-squares GBDT with exact search and check monotonicity on a dense grid in both directions.
def cotas_hijos(lo, hi, wl, wr, signo):
  # versión ingenua: los hijos heredan las cotas del padre
  return (lo, hi), (lo, hi)
Shift+Enter to run
QuizWhich paths an interaction constraint permits
With interaction_constraints = [[0, 1], [1, 2]], a tree's root splits on x1x_1 and its left child on x0x_0. Which features can its grandchild split on, and can any tree path use x0x_0 and x2x_2?
ProofAn interaction-constrained GBDT is a sum over sets
Prove: Let S\mathcal{S} be a family of feature sets and a GBDT whose trees obey the interaction constraint rule: at a node whose path used UU, splits use only features in ⋃S∈S, U⊆SS\bigcup_{S \in \mathcal{S},\, U \subseteq S} S. Then functions FSF_S exist, each depending only on xS\vb{x}_S, with F(x)=F0+∑S∈SFS(xS)F(\vb{x}) = F_0 + \sum_{S \in \mathcal{S}} F_S(\vb{x}_S).
0
Prove this for one tree; the model sums trees. Write each tree as a sum over leaves.

Step 1 of 4. What property do features UℓU_\ell on the root-to-leaf ℓ\ell path have?

QuizWhy dropped trees are shrunk
In a DART round k=4k = 4 trees are dropped. The new tree fits the model without them. Why is its weight 1/51/5 and the four dropped trees multiplied by 4/54/5?
QuizThe grid winner
In the tuning interactive with 20 000 rows, the best of 864 configurations gives validation 0.54140.5414 with seed 0. The same configuration gives 0.54200.5420 to 0.54390.5439 with seeds 1–5. What is the most precise explanation?
CodeA loss penalizing undershooting
Program a custom GBDT objective: asimetrica(y, F, a=3.0) must return gradient and Hessian with respect to margin F of asymmetric squared loss ℓ(y,F)=12v (y−F)2\ell(y, F) = \tfrac12 v\,(y - F)^2, with v=av = a if y>Fy > F (the model undershoots) and v=1v = 1 otherwise, row by row. Tests check derivatives by finite differences, that with a=1a = 1 the optimal constant prediction is the mean, and with a=3a = 3 it is the data's τ=0.75\tau = 0.75 expectile, value mm satisfying τ∑i(yi−m)+=(1−τ)∑i(m−yi)+\tau\sum_i (y_i - m)_+ = (1 - \tau)\sum_i (m - y_i)_+. They calculate the optimal constant with Newton iterations, as a GBDT's first leaf would.
import numpy as np

def asimetrica(y, F, a=3.0):
  # ahora mismo es la cuadrática simétrica
  g = F - y
  h = np.ones_like(F)
  return g, h
Shift+Enter to run
QuizWhat makes a benchmark unfair
A colleague compares XGBoost and LightGBM: for each, 50 Optuna trials with early stopping on validation, then publishes each best validation log-loss with one seed. What is most serious?

Tests deciding whether a difference between cross-validated models is real, such as the corrected resampled t-test, and comparisons among many models and datasets are covered in research methodology.

Summary

Key idea
The four GBDT libraries implement Newton boosting with different inductive biases and defaults: level-wise, leaf-wise or symmetric growth; categoricals by gradient or ordered statistics; missing values by learned direction or minimum. Those differences matter less than tuning any library well. Tune in phases (fixed rate with early stopping, complexity, sampling, regularization and finally lower rate), knowing phases interact and the search winner is selected under noise. Monotonic and interaction constraints encode domain knowledge with provable guarantees, and DART is an alternative to shrinkage for late-tree overspecialization.
  • Comparison. XGBoost: level-wise, 256-bin hist, η=0.3\eta = 0.3 and λ=1\lambda = 1. LightGBM: leaf-wise with 31 leaves, λ=0\lambda = 0 and 20 rows per leaf. CatBoost: depth-6 symmetric trees, ordered categorical statistics, missing as minimum. HistGB: leaf-wise, no GPU, at most 255 levels per categorical. Default comparison measures those choices, not libraries.
  • Rate and trees. With small η\eta the model depends on ηt\eta t and early stopping chooses T∗≈s∗/ηT^* \approx s^*/\eta: do not tune as two axes, and lower η\eta with proportionately higher tree maximum.
  • Phased recipe. Complexity (num_leaves or max_depth with minimum leaf), sampling, regularization, then lower rate. On the Higgs grid the recipe ties equal-budget random search, phase order changes results because complexity and λ\lambda regulate the same thing, and the best grid value is optimistic from seed noise.
  • Monotonicity. Local veto is insufficient. Propagating midpoint bounds [ℓ,m][\ell, m] to one child and [m,u][m, u] to the other and clipping weights guarantees monotonic trees and model. XGBoost and scikit-learn do this; LightGBM also has less conservative methods. A false constraint is bias data do not fix.
  • Interactions. Permitting at each node only features of sets containing those used makes the model a sum of functions of each set; singleton sets give a GAM.
  • DART. Randomly dropping trees each round, fitting the new one to the model without them and normalizing with 1/(k+1)1/(k + 1) and k/(k+1)k/(k + 1) flattens contribution profiles. It helps some problems, not all; it costs training time and destabilizes early stopping.
  • Fair benchmark. Same protocol and tuning budget, nested CV to measure on data unused in selection, several seeds with intervals, fixed versions and defaults as a baseline rather than a competitor.