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
- 11Ordered boosting and prediction shiftGradient-based one-side samplingLeaf-wise (best-first) tree growthHistogram-based split findingXGBoost regularized objectiveEarly stopping in boostingSuccessive halvingRandom searchNested cross-validation
- 00GPU software stackDependency resolution and lockingComplete seeding of a training run
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 AUC (paper table 2); compared with “optimal defaults” learned from the 38 datasets (, 4168 trees, depth 13, subsample , colsample_bytree ; table 3), it falls to . 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 and Hessians , a tree maximizing second-order gain and leaves with weight . Differences lie in five design decisions, most seen in the preceding two lessons.
| Decision | XGBoost 3.4 | LightGBM 4.7 | CatBoost 1.2 | HistGradientBoosting (scikit-learn 1.9) |
|---|---|---|---|---|
| Growth | level-wise, max_depth 6; optional grow_policy="lossguide" | leaf-wise, num_leaves 31, unlimited depth | symmetric (one split per level), depth 6 | leaf-wise, max_leaf_nodes 31 |
| Splits | default hist, 256 bins; optional exact and approx | 255-bin histogram; optional GOSS and EFB for sparse features | 254 CPU boundaries, 128 GPU | 255-bin histogram |
| Categoricals | enable_categorical: gradient partition, one-hot below 4 levels | gradient partition with smoothing (cat_smooth 10) and minimum group size | ordered target statistics and categorical combinations | gradient partition, at most 255 levels |
| Missing | learned default direction at each node | learned direction | nan_mode="Min": missing is less than all values | learned direction |
| Default regularization | , , min_child_weight 1 | , , min_data_in_leaf 20 | chosen from data, l2_leaf_reg 3, 1000 trees | , , min_samples_leaf 20; automatic early stopping above 10 000 rows |
| GPU | device="cuda" | only with GPU- or CUDA-compiled binary | task_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.
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 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:
- 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.
- Moderate rate and early stopping. Set between and , a generous maximum tree count, and early stopping with patience 50 to 200 rounds. Thereafter tree count is not tuned: stopping chooses it.
- Tree complexity.
num_leavesormax_depth, with minimum leaf size (min_data_in_leaf,min_child_weight,min_samples_leaf). This phase moves error most. - Sampling. Row fraction (
subsample,bagging_fraction) and column fraction (colsample_bytree,feature_fraction): stochastic boosting reduces variance and speeds up. - Regularization. (L2 on leaf weights), (L1) and (minimum split gain,
min_split_gainin LightGBM). - Lower rate last. Divide 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:
| Role | XGBoost | LightGBM | CatBoost | HistGB |
|---|---|---|---|---|
| rate | learning_rate (eta) | learning_rate | learning_rate | learning_rate |
| trees | n_estimators + early_stopping_rounds | num_iterations + early_stopping | iterations + od_wait | max_iter + n_iter_no_change |
| tree size | max_depth, max_leaves | num_leaves, max_depth | depth | max_leaf_nodes, max_depth |
| minimum leaf | min_child_weight (Hessian) | min_data_in_leaf, min_sum_hessian_in_leaf | min_data_in_leaf (non-symmetric) | min_samples_leaf |
| rows | subsample | bagging_fraction + bagging_freq | subsample (with bootstrap_type) | none |
| columns | colsample_bytree, _bylevel, _bynode | feature_fraction, feature_fraction_bynode | rsm (CPU only) | max_features (per node) |
| L2, L1, minimum gain | lambda, alpha, gamma | lambda_l2, lambda_l1, min_gain_to_split | l2_leaf_reg | l2_regularization |
Watch a units trap: XGBoost’s min_child_weight is a sum of Hessians, not rows. With logistic loss each row contributes , so min_child_weight requires at least 4 rows in a leaf with and 12 with . LightGBM’s min_data_in_leaf counts rows.
Rate and tree count go together
Why not tune and tree count simultaneously? With early stopping the latter is almost a function of the former. With shrinkage, each round does
an Euler step of size for differential equation in continuous “time” . If is small, the model after rounds depends on and almost solely through product : the same path traversed in shorter steps. Early stopping stops at time depending on data, not , so
This is a heuristic, not a theorem: the fitted tree is a discontinuous function of gradients, and with large steps stop following the path (each tree overshoots and the next corrects). The lab’s first cell checks this: training error at fixed barely changes between , and , separating at . In the interactive grid, the final recipe configuration with 2000 rows stops at 78 trees with and 390 with : exactly factor 5.
Two practical consequences follow. Tuning and tree count as two search axes wastes budget: almost the whole grid lies far from diagonal . And lowering 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 , min_data_in_leaf , feature_fraction and bagging_fraction , and lambda_l2 , with , 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.
There are four readings, each contradicting a common belief.
Defaults lose, more so with few data. With 2000 rows LightGBM defaults yield validation and test; the full recipe, with final phase, gives test. With 20 000 rows the gap halves ( versus ). 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 with 2000 rows and with 20 000; median random search at equal budget reaches and . 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 and , the optimum among 864 configurations (); normal recipe at 31 leaves, 160 rows per leaf, no sampling and (). Coordinate search is not order-invariant because controls interact: num_leaves, min_data_in_leaf and regulate the same thing, effective leaf size. With and Hessians around per row, a 400-row leaf’s weight is halved, and under that shrinkage bigger trees become good again; if complexity is fixed with , chosen trees are only optimal without regularization.
But the reverse order’s advantage is mostly luck. Its selected configuration uses feature_fraction , making its result seed-dependent. With seed 0, used by the grid, it yields validation; seeds 1–5 yield to , an interval containing normal recipe’s deterministic . On test, reverse yields with seed 0 and to with the other five; normal yields . With 2000 rows the same occurs: reverse wins validation ( versus , with bagging_fraction ), loses on other seeds ( to ) and loses on test ( versus ). 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 together.
The final phase delivers. With the recipe’s final configuration and , early stopping chooses 390 instead of 78 trees with 2000 rows, and 1037 instead of 221 with 20 000; test improves slightly in both ( and ). 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, , it suffices for each tree to be monotonic. The temptation is to enforce this locally: when searching for a split on feature , reject splits whose left weight exceeds right. This is insufficient. If the root splits on income with 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 containing every weight in its subtree (root ), and leaf weights are clipped to that interval: , also when calculating candidate split gains.
Proof
First, by induction from root, each node’s interval is nonempty and contained in its parent’s: because weights are clipped, so and intervals and are nonempty and within . Since each leaf weight is clipped to its interval, all leaves of node ‘s subtree have weights in .
Now take points and with , where has an increasing constraint. They travel together while splits use features other than , since they agree there. If they reach a leaf together, . Otherwise they separate at first node sending them to different sides, which must split feature at threshold such that : goes left and right. ’s leaf is in the left subtree and weighs at most ; ‘s is right and weighs at least . Hence .
A sum of increasing functions with positive coefficients is increasing, so model 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 is unnecessary for monotonicity (bounds already ensure it); it avoids accepting splits whose unclipped weights go against it and become two equal leaves at with no contribution. And note the cost: midpoint is conservative. A left subtree whose weights all lie far below 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.
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 where each summand depends only on one set’s features. With 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 , “only” 4. The model becomes highly sensitive to early-tree decisions. Shrinkage mitigates but does not resolve it.
Normalization is subtle. Let be the dropped contribution. Since the new tree fits what lacks, it learns approximately , times a typical dropped tree’s contribution. Simply adding it would yield : overshooting by counting the same thing twice. With normalization, if ,
prediction is preserved on average and the new tree has the same scale as each dropped tree after shrinkage ( versus ). XGBoost implements this normalization (normalize_type="tree", with learning rate in the denominator: ) 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 with DART versus with MART; in regression (CT slices, table 4), DART wins at all dataset sizes, e.g., L2 loss versus with 1000 trees (random forest ); in classification (face detection), MART wins 3 of 5 sizes, though best overall model is DART ( accuracy versus ). 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.
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 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 : 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 ; 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 , row loss is multiplied by , as are gradient and Hessian: , . Integer weight equals repeating the row 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 ceases to be a minimum if ; and initial margin does not tune itself (XGBoost leaves 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 : 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
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: and versus the true model’s , 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 and right with 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, and 64 bins.
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 : the true constraint removes variance. Unconstrained HistGradientBoostingClassifier decreases in 2127 intervals and with monotonic_cst none, with the same log-loss in each case ( and ); 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 , zero if and only if the income effect does not depend on age between those values. The free model reaches in margin for some customer: it invented an interaction absent from the additive true logit. With constraint separating age from the other two, or the additive constraint, mixed difference is on the order of , rounding error, as the decomposition theorem predicts; validation improves to and . HistGB with additive interaction_cst gives . 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.
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 :
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 () arrives with only 6 trees: later trees specialize in a few rows and worsen test. With the ratio drops to and error to , still improving at 146 trees. With DART the ratio is : the first tree ultimately contributes less than the hundredth, because every dropout multiplies its weight by . The profile is flat, as promised.
DART’s best test error greatly improves on MART without shrinkage, but not MART with . Its best arrives at 39 trees; at 150 it rises to : 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 and MART’s rate to see how much the conclusion depends on them.
Learning rate and tree count
The final browser cell checks heuristic with scikit-learn’s GradientBoostingRegressor (depth-3 trees) on Friedman 1: train at four rates to the same “time” and compare training error at matching times, and trees needed by each rate to fall below validation error .
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 , and , training error at the same time is nearly equal (at : , and ), although tree count ranges from 80 to 320; with the path differs ( at ), and 20 trees never reach the validation threshold. Trees needed to reach validation error scale as : 69, 133 and 267, with between and . Halving 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, ). 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 (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-learnTargetEncoder, using cross-fitting to avoid label leakage. - Reporting: outer-test log-loss and AUC, 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.
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))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 (AUC ), versus to for the others (AUC around ). 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 and : without categoricals, designs converge.
Defaults can be disastrous or excellent. Default XGBoost gives on credit-g (tuned ) and on Amazon, twice tuned (): and depth 6 with 500 training rows, or thousands-level categoricals split by gradient, overfit unchecked. Default CatBoost gives on credit-g, better than its “tuned” version (), and the same 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 (, and ) 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 and CatBoost by , 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
num_leaves = 255 and min_data_in_leaf = 1, and early stopping. What is the main risk?min_child_weight = 1 (default). In a region where the current model predicts for every row, how many rows must a leaf have at minimum for the split to be valid?cotas_hijos(lo, hi, wl, wr, signo), receiving node interval , 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)interaction_constraints = [[0, 1], [1, 2]], a tree's root splits on and its left child on . Which features can its grandchild split on, and can any tree path use and ?Step 1 of 4. What property do features on the root-to-leaf path have?
asimetrica(y, F, a=3.0) must return gradient and Hessian with respect to margin F of asymmetric squared loss , with if (the model undershoots) and otherwise, row by row. Tests check derivatives by finite differences, that with the optimal constant prediction is the mean, and with it is the data's expectile, value satisfying . 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, hTests 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
- Comparison. XGBoost: level-wise, 256-bin
hist, and . LightGBM: leaf-wise with 31 leaves, 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 the model depends on and early stopping chooses : do not tune as two axes, and lower with proportionately higher tree maximum.
- Phased recipe. Complexity (
num_leavesormax_depthwith 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 regulate the same thing, and the best grid value is optimistic from seed noise. - Monotonicity. Local veto is insufficient. Propagating midpoint bounds to one child and 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 and 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.