Skip to content

Gradient boosting libraries

scikit-learn’s HistGradientBoosting*, XGBoost and LightGBM build the same kind of model: many small trees, each fitted to the errors of the trees before it. They differ in parameter names, early stopping, category handling and logging. This page maps them side by side. The installed versions are scikit-learn 1.9, XGBoost 3.4 and LightGBM 4.7. The examples use data/customers.csv (churn). The blocks share one session:

import lightgbm as lgb
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from threadpoolctl import threadpool_limits
from xgboost import XGBClassifier
threadpool_limits(limits=1) # one OpenMP thread: faster on small tables
customers = pd.read_csv("data/customers.csv")
CAT = ["region", "plan", "contract", "payment_method"]
X = customers.drop(columns=["customer_id", "signup_date", "churned"])
y = customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
cat_dtypes = {c: pd.CategoricalDtype(sorted(X_train[c].unique())) for c in CAT}
def to_categories(df: pd.DataFrame) -> pd.DataFrame:
"""Apply the training categories; unseen values become NaN."""
out = df.copy()
for col, dtype in cat_dtypes.items():
out[col] = out[col].where(out[col].isin(dtype.categories)).astype(dtype)
return out
X_train, X_test = to_categories(X_train), to_categories(X_test)
X_fit, X_val, y_fit, y_val = train_test_split( # a validation set for early stopping
X_train, y_train, test_size=0.2, stratify=y_train, random_state=42
)
print(X_train.dtypes.map(str).value_counts().to_dict())
Output
{'int64': 5, 'category': 4, 'float64': 3}

threadpool_limits(limits=1) keeps the three libraries on one thread. On a few thousand rows, threads cost more than they save; scores do not change.

I want to… Use… Notes
a strong tabular model with no extra install HistGradientBoostingClassifier(), HistGradientBoostingRegressor() scikit-learn
the fastest training on large data lgb.LGBMClassifier(verbose=-1) leaf-wise trees
GPU training XGBClassifier(device="cuda")
use text columns as categories df[col].astype(pd.CategoricalDtype(train_categories)) all three read category
map unseen categories to missing s.where(s.isin(dtype.categories)).astype(dtype) no pandas 3 warning
early stopping in HGB early_stopping=True, n_iter_no_change=30, validation_fraction=0.2 "auto" only above 10,000 rows
early stopping in XGBoost XGBClassifier(early_stopping_rounds=50, eval_metric="auc"), fit(..., eval_set=[(X_val, y_val)]) settings in the constructor
early stopping in LightGBM fit(..., eval_X=X_val, eval_y=y_val, callbacks=[lgb.early_stopping(50, verbose=False)]) eval_set is deprecated in 4.7
the number of trees kept hgb.n_iter_, xgb.best_iteration + 1, lgbm.best_iteration_
predict with the first k trees xgb.predict_proba(X, iteration_range=(0, k)), lgbm.predict_proba(X, num_iteration=k)
the validation curve per round hgb.validation_score_, xgb.evals_result(), lgbm.evals_result_
a silent LightGBM verbose=-1 in the constructor
a silent XGBoost fit(..., verbose=False) verbosity=0 for warnings
the same LightGBM model on every run random_state=42, deterministic=True, force_row_wise=True
fewer threads on small data n_jobs=1 or threadpool_limits(limits=1) avoids oversubscription
weight the rare class scale_pos_weight=n_neg / n_pos (XGBoost, LightGBM), class_weight="balanced"
a monotonic effect monotonic_cst= (HGB), monotone_constraints= (XGBoost, LightGBM)
a quantile or Poisson model loss="quantile" / "poisson" (HGB), objective="quantile" (LightGBM)
gain importances xgb.feature_importances_, lgbm.booster_.feature_importance("gain")
model-agnostic importances sklearn.inspection.permutation_importance(model, X_val, y_val) all three
save the trees in a portable file xgb.save_model("m.json"), lgbm.booster_.save_model("m.txt")
load them back m = XGBClassifier(); m.load_model("m.json"); lgb.Booster(model_file="m.txt") Booster.predict gives P(class 1)
tune with CV RandomizedSearchCV or Optuna on the sklearn wrappers see CV and tuning
Task HistGradientBoosting XGBoost LightGBM
a classifier / regressor HistGradientBoostingClassifier / ...Regressor XGBClassifier / XGBRegressor LGBMClassifier / LGBMRegressor
the number of trees max_iter=100 n_estimators=100 n_estimators=100
the step size learning_rate=0.1 learning_rate=0.3 learning_rate=0.1
the tree size max_leaf_nodes=31, max_depth=None max_depth=6, max_leaves=0 num_leaves=31, max_depth=-1
the minimum rows per leaf min_samples_leaf=20 min_child_weight=1 (hessian sum) min_child_samples=20
an L2 penalty l2_regularization=0 reg_lambda=1 reg_lambda=0
an L1 penalty — reg_alpha=0 reg_alpha=0
a minimum gain to split — gamma=0 min_split_gain=0
row subsampling — subsample=1 subsample=1.0, subsample_freq=0 (set it to 1 to sample)
column subsampling max_features=1.0 (per split) colsample_bytree=1 colsample_bytree=1
histogram bins max_bins=255 max_bin=256 max_bin=255 (a constructor keyword)
early stopping early_stopping=True early_stopping_rounds=50 + eval_set callbacks=[lgb.early_stopping(50)] + eval_X, eval_y
the validation data internal validation_fraction=0.1 fit(..., eval_set=[(X_val, y_val)]) fit(..., eval_X=X_val, eval_y=y_val)
the monitored metric scoring="loss" eval_metric="auc" (constructor) fit(..., eval_metric="auc")
the trees used to predict n_iter_ best_iteration + 1 best_iteration_
native categories category dtype (categorical_features="from_dtype") category dtype (enable_categorical) category dtype (automatic)
missing values native native native
class imbalance class_weight="balanced" scale_pos_weight=n_neg / n_pos class_weight="balanced" or scale_pos_weight
monotonic effects monotonic_cst={"tenure_months": -1} monotone_constraints={"tenure_months": -1} monotone_constraints=[...] (one per column)
the loss loss="log_loss", "poisson", "quantile" objective="binary:logistic", "reg:squarederror" objective="binary", "regression", "quantile"
a seed random_state=42 random_state=42 random_state=42
threads OpenMP (threadpool_limits) n_jobs n_jobs
silence quiet by default verbose=False in fit; verbosity=0 verbose=-1 (constructor)
feature importances permutation_importance feature_importances_ (gain) feature_importances_ (importance_type="split")
save the model alone joblib.dump model.save_model("m.json") model.booster_.save_model("m.txt")
a GPU — device="cuda" device="gpu" (special build)

The numbers after = are the defaults in the installed versions.

hgb = HistGradientBoostingClassifier(
learning_rate=0.05, max_iter=1000, early_stopping=True, # "auto": only >10,000 rows
n_iter_no_change=30, validation_fraction=0.2, random_state=42,
).fit(X_train, y_train) # splits its own validation set from X_train
xgb = XGBClassifier(
n_estimators=1000, learning_rate=0.05, max_depth=4, early_stopping_rounds=50,
eval_metric="auc", random_state=42, n_jobs=1, # both in the constructor
).fit(X_fit, y_fit, eval_set=[(X_val, y_val)], verbose=False)
lgbm = lgb.LGBMClassifier(
n_estimators=1000, learning_rate=0.05, num_leaves=15, random_state=42,
n_jobs=1, verbose=-1,
).fit(X_fit, y_fit, eval_X=X_val, eval_y=y_val, eval_metric="auc",
callbacks=[lgb.early_stopping(50, verbose=False)])
used = {"hgb": hgb.n_iter_, "xgb": xgb.best_iteration + 1, "lgbm": lgbm.best_iteration_}
stored = {"hgb": hgb.n_iter_, "xgb": xgb.get_booster().num_boosted_rounds(),
"lgbm": lgbm.booster_.num_trees()}
for name, model in [("hgb", hgb), ("xgb", xgb), ("lgbm", lgbm)]:
auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
print(f"{name:<5} used {used[name]:>3} stored {stored[name]:>3}", f"AUC {auc:.3f}")
Output
hgb used 66 stored 66 AUC 0.829
xgb used 68 stored 118 AUC 0.836
lgbm used 45 stored 45 AUC 0.837
HistGradientBoosting XGBoost LightGBM
turn it on early_stopping=True ("auto" = on above 10,000 rows) early_stopping_rounds=k lgb.early_stopping(k) callback
validation data a fraction of fit’s rows (validation_fraction) eval_set=[(X_val, y_val)] (last pair is monitored) eval_X=, eval_y= (a tuple for several)
patience n_iter_no_change=10, tol=1e-7 early_stopping_rounds stopping_rounds, min_delta
monitored scoring="loss" or any scorer name the last eval_metric every metric; first_metric_only=True for one
after stopping keeps all n_iter_ trees, including the last n_iter_no_change that did not improve: no rollback stores every tree; predict uses best_iteration + 1 by default the booster holds best_iteration_ trees
best score validation_score_.max() (negative loss by default) best_score best_score_["valid_0"]["auc"]
history train_score_, validation_score_ evals_result()["validation_0"] evals_result_["valid_0"]
p_best = xgb.predict_proba(X_test)[:, 1] # best iteration by default
p_all = xgb.predict_proba(X_test, iteration_range=(0, stored["xgb"]))[:, 1]
p_20 = lgbm.predict_proba(X_test, num_iteration=20)[:, 1] # only the first 20 trees
print(f"xgb best {roc_auc_score(y_test, p_best):.3f}",
f"xgb all trees {roc_auc_score(y_test, p_all):.3f}",
f"lgbm 20 trees {roc_auc_score(y_test, p_20):.3f}")
print(list(xgb.evals_result()["validation_0"]), list(lgbm.evals_result_["valid_0"]))
Output
xgb best 0.836 xgb all trees 0.838 lgbm 20 trees 0.817
['auc'] ['auc', 'binary_logloss']

Here all 118 XGBoost trees score a little higher on the test set than the best 68: with 750 validation rows, the stopping point is noisy. Early stopping uses the validation rows to choose the number of trees, so they are no longer a fair test set. Keep a separate test set, as above, or choose the number of trees inside cross-validation.

HistGradientBoosting XGBoost LightGBM
how to mark category dtype; or categorical_features=["region", ...] or a boolean mask category dtype; enable_categorical is on by default in 3.4 category dtype; or fit(..., categorical_feature=[...])
text columns (str) ValueError: could not convert string to float ValueError about dtypes ValueError: pandas dtypes must be int, float or bool
unseen category at predict time treated as missing treated as missing treated as missing
cardinality limit at most max_bins (255) categories per column none none (rare ones merged via min_data_per_group)
split method partitions sorted by gradient partitions; one-hot below max_cat_to_onehot partitions; one-hot below max_cat_to_onehot=4
main knobs max_bins max_cat_to_onehot, max_cat_threshold cat_smooth, cat_l2, max_cat_threshold
new = X.loc[X_test.index[:2]].copy() # raw rows with text columns
new.loc[new.index[0], "region"] = "Central" # a region never seen in training
new = to_categories(new) # Central -> NaN, without a warning
print(new["region"].tolist())
print(lgbm.predict_proba(new)[:, 1].round(3), xgb.predict_proba(new)[:, 1].round(3))
Output
[nan, 'East']
[0.089 0.458] [0.105 0.456]

Build the CategoricalDtype once, from the training rows, and apply it to every later frame. astype(dtype) with values outside the categories still works in pandas 3.1, but it warns (Pandas4Warning) and will raise in a future version. Mask unknown values first, as to_categories does.

Need HistGradientBoosting XGBoost LightGBM
no training log default (verbose=0) fit(..., verbose=False); verbosity=0 silences warnings too verbose=-1 in the constructor
no early-stopping message — — lgb.early_stopping(50, verbose=False)
log every k rounds verbose=1 fit(..., verbose=k) callbacks=[lgb.log_evaluation(k)]
the same model on each run random_state=42 random_state=42 random_state=42
the same model across thread counts not guaranteed: fix the thread count not guaranteed: fix n_jobs deterministic=True, force_row_wise=True
GPU runs — can differ slightly between runs can differ slightly between runs
def fit_lgbm() -> np.ndarray:
model = lgb.LGBMClassifier(n_estimators=100, learning_rate=0.05, subsample=0.8,
subsample_freq=1, colsample_bytree=0.8,
random_state=42, n_jobs=1, verbose=-1,
deterministic=True, force_row_wise=True)
return model.fit(X_train, y_train).predict_proba(X_test)[:, 1]
print(np.array_equal(fit_lgbm(), fit_lgbm())) # same seed, same data: identical
Output
True
Type HistGradientBoosting XGBoost LightGBM Meaning
split count — get_score(importance_type="weight") importance_type="split" (default) how often a feature is used
gain — feature_importances_ (normalized "gain") importance_type="gain" the loss reduction it brings
cover — get_score(importance_type="cover") — rows affected
permutation permutation_importance(model, X_val, y_val) same same the score drop when shuffled; model-agnostic
SHAP shap.TreeExplainer (numeric features only; with native categories, shap.Explainer(model.predict_proba, masker)) predict(..., pred_contribs=True) on a DMatrix predict(X, pred_contrib=True) per-row contributions
imp = pd.DataFrame({
"lgbm_split": lgbm.feature_importances_,
"lgbm_gain": lgbm.booster_.feature_importance(importance_type="gain").round(0),
"xgb_gain": xgb.feature_importances_.round(3),
}, index=X_train.columns)
print(imp.sort_values("lgbm_gain", ascending=False).head(5))
Output
lgbm_split lgbm_gain xgb_gain
tenure_months 66 3089.0 0.261
contract 55 1774.0 0.234
monthly_charges 120 1319.0 0.058
age 135 1197.0 0.055
support_tickets 83 1194.0 0.097

Split counts favor continuous columns with many split points. Rank by gain or by permutation importance on validation data.

from pathlib import Path
Path("output").mkdir(exist_ok=True)
xgb.save_model("output/churn_xgb.json") # JSON: stable across XGBoost versions
lgbm.booster_.save_model("output/churn_lgbm.txt") # text: the best iteration only
xgb2 = XGBClassifier()
xgb2.load_model("output/churn_xgb.json")
booster = lgb.Booster(model_file="output/churn_lgbm.txt") # predict() gives P(class 1)
print(np.allclose(xgb2.predict_proba(X_test)[:, 1], p_best),
np.allclose(booster.predict(X_test), lgbm.predict_proba(X_test)[:, 1]))
Output
True True

A native file stores the trees only. Save the preprocessing (here the category lists) next to it, or save the whole pipeline with joblib.

  1. Fix learning_rate at 0.05–0.1 and let early stopping choose the number of trees.
  2. Tune the tree size: max_leaf_nodes / num_leaves (8–64) or max_depth (3–8).
  3. Tune the leaf size: min_samples_leaf / min_child_samples (10–200), min_child_weight (1–20).
  4. Add randomness: subsample 0.6–1 (LightGBM: with subsample_freq=1), colsample_bytree 0.5–1.
  5. Add penalties: l2_regularization / reg_lambda (log scale, 1e-3 to 10).
  6. Lower learning_rate for the final model and let early stopping add trees.
Native API XGBoost LightGBM
data xgboost.DMatrix(X, y, enable_categorical=True) lgb.Dataset(X, y)
train xgboost.train(params, dtrain, num_boost_round, evals=[(dval, "val")], early_stopping_rounds=50) lgb.train(params, dtrain, num_boost_round, valid_sets=[dval], callbacks=[...])
CV xgboost.cv(params, dtrain, nfold=5) lgb.cv(params, dtrain, nfold=5)
when custom objectives, ranking, very large data same
Trap Symptom Fix
LightGBM fit(eval_set=...) a deprecation warning in 4.7 eval_X= and eval_y=
LightGBM without verbose=-1 [LightGBM] [Info] ... lines on stdout verbose=-1 in the constructor
LightGBM subsample=0.8 alone no row sampling happens add subsample_freq=1
XGBoost early_stopping_rounds in fit TypeError in XGBoost 3 put it and eval_metric in the constructor
XGBoost fit without verbose=False one log line per round verbose=False
HGB on a small table early stopping is off ("auto" needs >10,000 rows) early_stopping=True
HGB n_iter_ read as the best round it includes the last n_iter_no_change rounds expected: HGB has no rollback
XGBoost predict after early stopping — uses the best iteration; pass iteration_range to change it
text (str) columns ValueError in all three category dtype, or encode
astype("category") on train and test separately different category lists one CategoricalDtype from the training rows
unseen values in astype(dtype) Pandas4Warning in pandas 3.1 mask them with where(isin(...)) first
HGB with more than 255 categories ValueError about cardinality TargetEncoder, or LightGBM / XGBoost
the early-stopping set used as the test set an optimistic score a separate test set
all cores on a small table, or several fits in parallel slow fits, oversubscription n_jobs=1 or threadpool_limits(limits=1)
criterion="friedman_mse" on GradientBoosting* deprecated in scikit-learn 1.9 leave the default
split-count importances high-cardinality columns rank first gain or permutation importance