Skip to content

LightGBM

LightGBM is a gradient boosting library built for speed. Histogram-based split finding makes it fast to train. It also grows trees leaf-wise instead of the level-wise approach XGBoost uses by default, which often makes it more accurate on large datasets.

Every code block runs in a container in the companion repository, so the numbers are real.

from pathlib import Path
import lightgbm as lgb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.metrics import classification_report, roc_auc_score
from sklearn.model_selection import (
StratifiedKFold,
cross_val_score,
train_test_split,
)
out = Path("outputs")
out.mkdir(exist_ok=True)
features, y = make_classification(n_samples=2000,
n_features=20,
n_informative=10,
n_redundant=3,
weights=[0.7, 0.3],
flip_y=0.05,
random_state=42)
feature_names = [f"feature_{i}" for i in range(features.shape[1])]
x_train, x_test, y_train, y_test = train_test_split(features,
y,
test_size=0.2,
random_state=42,
stratify=y)
model = lgb.LGBMClassifier(n_estimators=100,
max_depth=4,
learning_rate=0.1,
num_leaves=31,
random_state=42,
verbose=-1)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, x_train, y_train, cv=cv, scoring="roc_auc")
print(f"Cross-validated ROC-AUC: {scores.mean():.4f} (+/- {scores.std():.4f})")
model.fit(x_train, y_train)
y_prob = model.predict_proba(x_test)[:, 1]
print(f"Test ROC-AUC: {roc_auc_score(y_test, y_prob):.4f}")
print(classification_report(y_test,
model.predict(x_test),
target_names=["Negative", "Positive"]))
Cross-validated ROC-AUC: 0.9275 (+/- 0.0230)
Test ROC-AUC: 0.9480
precision recall f1-score support
Negative 0.92 0.94 0.93 276
Positive 0.86 0.81 0.83 124
accuracy 0.90 400
macro avg 0.89 0.87 0.88 400
weighted avg 0.90 0.90 0.90 400

XGBoost grows level by level: every node at one depth is split before the next depth. LightGBM grows leaf-wise, always splitting the leaf with the highest loss reduction.

Level-wise (XGBoost): Leaf-wise (LightGBM):
[root] [root]
/ \ / \
[L1] [L1] [L1] [L1]
/ \ / \ / \
[L2][L2][L2][L2] [L2] [L2]
/ \
[L3] [L3]

Leaf-wise growth yields deeper trees with fewer leaves. It often improves accuracy but can overfit on small data. num_leaves is the primary complexity control: set it lower (15 to 31) for small datasets.

LightGBM handles categorical features directly, without one-hot encoding. Mark columns as category dtype and pass them to fit via categorical_feature.

A small simulated clinical table has five numeric columns and three categorical ones. The outcome depends on glucose, BMI, smoking, family history, and exercise. The CatBoost page uses a table with the same column names, but its target follows a different formula and it adds diagnosis and department columns. The two datasets differ, so do not compare scores across the two pages.

np.random.seed(42)
n = 2000
clinical = pd.DataFrame({
"age": np.random.normal(55, 15, n).astype(int),
"bmi": np.random.normal(27, 5, n).round(1),
"glucose": np.random.lognormal(4.6, 0.3, n).round(1),
"cholesterol": np.random.normal(200, 40, n).round(0),
"blood_pressure": np.random.normal(130, 20, n).astype(int),
"smoking": pd.Categorical(
np.random.choice(["never", "former", "current"], n)),
"exercise": pd.Categorical(
np.random.choice(["none", "moderate", "heavy"], n)),
"family_history": pd.Categorical(np.random.choice(["yes", "no"], n)),
})
logit = (0.03 * clinical["glucose"] + 0.12 * clinical["bmi"]
+ (clinical["smoking"] == "current").astype(int) * 1.8
+ (clinical["family_history"] == "yes").astype(int) * 1.3
+ (clinical["exercise"] == "none").astype(int) * 0.9 - 9)
clinical["target"] = (
np.random.rand(n) < 1 / (1 + np.exp(-logit))).astype(int)
x_train_cat, x_test_cat, y_train_cat, y_test_cat = train_test_split(
clinical.drop(columns=["target"]),
clinical["target"],
test_size=0.2,
random_state=42,
stratify=clinical["target"])
cat_features = ["smoking", "exercise", "family_history"]
model_cat = lgb.LGBMClassifier(n_estimators=200,
num_leaves=31,
learning_rate=0.1,
random_state=42,
verbose=-1)
model_cat.fit(x_train_cat, y_train_cat, categorical_feature=cat_features)
predicted_probability = model_cat.predict_proba(x_test_cat)[:, 1]
roc_auc = roc_auc_score(y_test_cat, predicted_probability)
print(f"ROC-AUC with native categoricals: {roc_auc:.4f}")
ROC-AUC with native categoricals: 0.7846

LightGBM finds optimal splits by grouping category values rather than expanding them into one-hot columns, which is far more efficient for high-cardinality categoricals.

configs = [
{"n_estimators": 100, "max_depth": -1, "num_leaves": 31,
"learning_rate": 0.1},
{"n_estimators": 200, "max_depth": -1, "num_leaves": 31,
"learning_rate": 0.1},
{"n_estimators": 200, "max_depth": -1, "num_leaves": 63,
"learning_rate": 0.1},
{"n_estimators": 200, "max_depth": 5, "num_leaves": 31,
"learning_rate": 0.05},
{"n_estimators": 300, "max_depth": -1, "num_leaves": 31,
"learning_rate": 0.05},
{"n_estimators": 300, "max_depth": 7, "num_leaves": 63,
"learning_rate": 0.05},
]
best_score, best_cfg = 0, None
for cfg in configs:
candidate = lgb.LGBMClassifier(random_state=42, verbose=-1, **cfg)
score = cross_val_score(candidate, x_train, y_train, cv=cv,
scoring="roc_auc").mean()
print(f" n_est={cfg['n_estimators']:>3}, "
f"depth={cfg['max_depth']:>2}, "
f"leaves={cfg['num_leaves']:>2}, "
f"lr={cfg['learning_rate']:.2f} -> ROC-AUC={score:.4f}")
if score > best_score:
best_score, best_cfg = score, cfg
best_model = lgb.LGBMClassifier(random_state=42, verbose=-1, **best_cfg)
best_model.fit(x_train, y_train)
tuned_prob = best_model.predict_proba(x_test)[:, 1]
print(f"Best ROC-AUC: {best_score:.4f}")
print(f"Tuned Test ROC-AUC: {roc_auc_score(y_test, tuned_prob):.4f}")
n_est=100, depth=-1, leaves=31, lr=0.10 -> ROC-AUC=0.9349
n_est=200, depth=-1, leaves=31, lr=0.10 -> ROC-AUC=0.9366
n_est=200, depth=-1, leaves=63, lr=0.10 -> ROC-AUC=0.9351
n_est=200, depth= 5, leaves=31, lr=0.05 -> ROC-AUC=0.9335
n_est=300, depth=-1, leaves=31, lr=0.05 -> ROC-AUC=0.9365
n_est=300, depth= 7, leaves=63, lr=0.05 -> ROC-AUC=0.9340
Best ROC-AUC: 0.9366
Tuned Test ROC-AUC: 0.9554

The default num_leaves=31 wins here (best ROC-AUC 0.9366, tuned test 0.9554). Increasing to 63 does not help, because the dataset is not large enough to need more complex trees.

importance = pd.DataFrame({
"feature": feature_names,
"importance": best_model.feature_importances_,
}).sort_values("importance", ascending=False)
print(importance.head(6).to_string(index=False))
feature importance
feature_3 550
feature_0 466
feature_14 431
feature_16 422
feature_4 419
feature_9 393
top15 = importance.head(15)
fig, ax = plt.subplots(figsize=(6, 5))
ax.barh(top15["feature"][::-1], top15["importance"][::-1], color="#55a868")
ax.set_xlabel("Split count")
ax.set_title("LightGBM feature importance (top 15)")
fig.tight_layout()
fig.savefig(out / "lightgbm-feature-importance.png", dpi=150)
plt.close(fig)

LightGBM feature importance, top 15 by split count

LightGBM reports importance as the split count (how often a feature is used), which differs from XGBoost’s gain-based importance. Both are valid, but they measure different things.

x_train_es, x_validation, y_train_es, y_val = train_test_split(
x_train, y_train, test_size=0.2, random_state=42, stratify=y_train
)
model_es = lgb.LGBMClassifier(n_estimators=1000,
num_leaves=31,
learning_rate=0.05,
random_state=42,
verbose=-1)
model_es.fit(
x_train_es,
y_train_es,
eval_X=x_validation,
eval_y=y_val,
callbacks=[lgb.early_stopping(20, verbose=False),
lgb.log_evaluation(0)])
best_logloss = model_es.best_score_["valid_0"]["binary_logloss"]
print(f"Best iteration: {model_es.best_iteration_}")
print(f"Best validation logloss: {best_logloss:.4f}")
Best iteration: 157
Best validation logloss: 0.2164

LightGBM uses callbacks: lgb.early_stopping(20) stops when the validation metric does not improve for 20 rounds, lgb.log_evaluation(0) silences the logs. The eval_X and eval_y arguments arrived in LightGBM 4.7.0, which deprecates the older eval_set=[(x_validation, y_val)]. On an earlier LightGBM, pass eval_set instead.

LightGBM’s speed comes from histogram-based split finding, which bins each feature before the search for splits. The LightGBM documentation lists leaf-wise growth among its accuracy features. XGBoost has also binned features into histograms by default since version 2.0, so time the two on your own data before you choose on speed alone. The block below fits both with the same number of trees and the same depth on 50,000 rows and 50 features.

import sys
import time
import xgboost as xgb
x_large, y_large = make_classification(n_samples=50000,
n_features=50,
n_informative=20,
random_state=42)
start = time.perf_counter()
xgb.XGBClassifier(n_estimators=200, max_depth=6,
random_state=42).fit(x_large, y_large)
xgb_seconds = time.perf_counter() - start
start = time.perf_counter()
lgb.LGBMClassifier(n_estimators=200, max_depth=6, random_state=42,
verbose=-1).fit(x_large, y_large)
lgb_seconds = time.perf_counter() - start
# Wall-clock times change from run to run, so they go to stderr and stay
# off the page.
print(f"XGBoost: {xgb_seconds:.2f}s", file=sys.stderr)
print(f"LightGBM: {lgb_seconds:.2f}s", file=sys.stderr)
print(f"Speedup: {xgb_seconds / lgb_seconds:.1f}x", file=sys.stderr)

LightGBM fit faster than XGBoost in every run behind this page. The ratio moved a lot from run to run, because it depends on the hardware, the thread count, and the other work on the machine, so the page does not quote it.

Feature LightGBM XGBoost
Tree growth Leaf-wise Level-wise
Complexity control num_leaves max_depth
Categoricals Native Native with enable_categorical=True
Speed Very fast Fast
Overfitting on small data Higher risk Lower risk

The next page covers CatBoost, which takes a different approach to categorical features and uses ordered boosting to reduce overfitting.

Ke and colleagues, 2017 describe LightGBM, a fast implementation of gradient boosting decision trees.

Chen and Guestrin, 2016 describe XGBoost, a scalable system for gradient tree boosting.

  • LightGBM classifier reference

    The reference defines fit-time evaluation inputs, categorical features, and feature importance. Match the reference version to the installed library before selecting early-stopping arguments.

  • scikit-learn cross-validation guide

    The guide separates model selection from final evaluation. Use that separation when choosing boosting rounds or comparing several parameter settings.