Skip to content

LightGBM

LightGBM is a gradient boosted tree library built for speed. It bins each feature into a histogram before training and grows trees leaf by leaf, so it trains fast on wide tables and handles a pandas category column without one-hot encoding. Every block below ran with LightGBM 4.7.

Task Call
Classifier lgb.LGBMClassifier(n_estimators=1000, learning_rate=0.05)
Validation set fit(x, y, eval_X=(x_valid,), eval_y=(y_valid,))
Early stopping callbacks=[lgb.early_stopping(stopping_rounds=50)]
Gain importance booster.feature_importance(importance_type="gain")
SHAP values model.predict(x, pred_contrib=True)
Raw score model.predict(x, raw_score=True)
Native training lgb.train(params, dtrain, valid_sets=[dvalid], callbacks=[...])
Cross-validation lgb.cv(params, dtrain, nfold=5, stratified=True)
Imbalanced classes LGBMClassifier(class_weight="balanced") or is_unbalance=True
Regression lgb.LGBMRegressor()
Save booster.save_model("model.txt", num_iteration=...)

The simulated table has a thousand samples with 30 genes and a cell type label. The outcome depends on Gene_01, Gene_02, the product of Gene_03 and Gene_04, and the cell type; the other 26 genes are noise. Training rows fit the trees, validation rows decide when to stop, and test rows give the final score.

from pathlib import Path
import lightgbm as lgb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.metrics import (
accuracy_score, r2_score, recall_score, roc_auc_score,
root_mean_squared_error,
)
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(42)
Path("outputs").mkdir(exist_ok=True)
n_samples, n_genes = 1000, 30
genes = [f"Gene_{i:02d}" for i in range(1, n_genes + 1)]
expr = pd.DataFrame(rng.normal(size=(n_samples, n_genes)), columns=genes)
cell_type = rng.choice(["B_cell", "Monocyte", "T_cell"], size=n_samples)
cell_shift = pd.Series(cell_type).map(
{"B_cell": -1.0, "Monocyte": 1.0, "T_cell": 0.0}
)
logit = (2.0 * expr["Gene_01"] - 1.5 * expr["Gene_02"]
+ 1.5 * expr["Gene_03"] * expr["Gene_04"] + cell_shift)
label = rng.binomial(1, 1 / (1 + np.exp(-logit)))
expr["cell_type"] = pd.Categorical(cell_type)
x_rest, x_test, y_rest, y_test = train_test_split(
expr, label, test_size=0.2, stratify=label, random_state=42
)
x_train, x_valid, y_train, y_valid = train_test_split(
x_rest, y_rest, test_size=0.25, stratify=y_rest, random_state=42
)
print(f"train {len(x_train)}, valid {len(x_valid)}, test {len(x_test)}")
train 600, valid 200, test 200

Early stopping is a callback. Training stops when the validation log loss has not improved for 50 rounds. The category column is picked up as categorical on its own, since fit defaults to categorical_feature="auto".

model = lgb.LGBMClassifier(
n_estimators=1000,
learning_rate=0.05,
num_leaves=15,
min_child_samples=20,
subsample=0.8,
subsample_freq=1,
colsample_bytree=0.8,
random_state=42,
n_jobs=1,
deterministic=True,
force_row_wise=True,
verbose=-1,
)
model.fit(
x_train, y_train,
eval_X=(x_valid,), eval_y=(y_valid,), eval_names=["valid"],
eval_metric="binary_logloss",
callbacks=[lgb.early_stopping(stopping_rounds=50, verbose=False)],
)
best_loss = model.best_score_["valid"]["binary_logloss"]
print(f"best iteration = {model.best_iteration_}")
print(f"best validation log loss = {best_loss:.4f}")
best iteration = 106
best validation log loss = 0.4216

Three API changes trip up older tutorials:

Older call LightGBM 4.7
fit(..., eval_set=[(x_valid, y_valid)]) fit(..., eval_X=(x_valid,), eval_y=(y_valid,)); eval_set still runs but warns that it is deprecated
fit(..., early_stopping_rounds=50) callbacks=[lgb.early_stopping(50)]
fit(..., verbose=10) callbacks=[lgb.log_evaluation(10)]

subsample has no effect unless subsample_freq is above 0. n_jobs=1, deterministic=True, and force_row_wise=True make a run repeat exactly, and verbose=-1 silences the training log.

After early stopping, predict and predict_proba use the best iteration.

test_prob = model.predict_proba(x_test)[:, 1]
test_pred = model.predict(x_test)
print(f"test accuracy = {accuracy_score(y_test, test_pred):.3f}")
print(f"test ROC AUC = {roc_auc_score(y_test, test_prob):.3f}")
test accuracy = 0.820
test ROC AUC = 0.899

"split" counts how often a feature is used, and it is the default for the scikit-learn classes. "gain" sums the loss reduction from those splits and ranks real signal more reliably.

booster = model.booster_
importance = pd.DataFrame({
"split": booster.feature_importance(importance_type="split"),
"gain": booster.feature_importance(importance_type="gain"),
}, index=booster.feature_name()).sort_values("gain", ascending=False)
print(importance.head(6).round(1))
split gain
Gene_01 159 1407.7
Gene_02 161 1230.2
cell_type 63 324.6
Gene_03 73 269.9
Gene_04 69 263.6
Gene_16 59 193.0
fig, ax = plt.subplots(figsize=(6, 4))
lgb.plot_importance(model, importance_type="gain", max_num_features=10,
precision=0, height=0.6, grid=False, ax=ax)
ax.set(title="Top 10 features by gain", xlabel="total gain")
fig.tight_layout()
fig.savefig("outputs/lightgbm-importance.png", dpi=150)
plt.close(fig)

Horizontal bars of total gain for the top 10 features. Gene_01 leads with 1408 and Gene_02 follows with 1230. cell_type has 325, Gene_03 270, and Gene_04 264, and five noise genes follow with between 155 and 193.

pred_contrib=True returns one SHAP value per feature per sample plus a final bias column, as on the XGBoost page. Each row sums to the raw score, the log-odds that raw_score=True returns.

contrib = model.predict(x_test, pred_contrib=True)
raw = model.predict(x_test, raw_score=True)
print(f"shape {contrib.shape}: {len(x_test)} samples, "
f"{x_test.shape[1]} features + bias")
print(f"rows sum to the raw score: {np.allclose(contrib.sum(axis=1), raw)}")
mean_abs = pd.Series(np.abs(contrib[:, :-1]).mean(axis=0),
index=x_test.columns)
print(mean_abs.sort_values(ascending=False).head(5).round(3))
shape (200, 32): 200 samples, 31 features + bias
rows sum to the raw score: True
Gene_01 1.232
Gene_02 1.022
cell_type 0.412
Gene_04 0.152
Gene_16 0.139
dtype: float64

The native API takes a Dataset and a parameter dictionary. The names differ from the scikit-learn class: num_threads for n_jobs, bagging_fraction and bagging_freq for subsample and subsample_freq, feature_fraction for colsample_bytree, and min_data_in_leaf for min_child_samples. Build the validation set with reference=dtrain so it reuses the training bins.

dtrain = lgb.Dataset(x_train, label=y_train)
dvalid = lgb.Dataset(x_valid, label=y_valid, reference=dtrain)
params = {
"objective": "binary",
"metric": "binary_logloss",
"learning_rate": 0.05,
"num_leaves": 15,
"min_data_in_leaf": 20,
"bagging_fraction": 0.8,
"bagging_freq": 1,
"feature_fraction": 0.8,
"num_threads": 1,
"deterministic": True,
"force_row_wise": True,
"seed": 42,
"verbose": -1,
}
evals = {}
native = lgb.train(
params, dtrain, num_boost_round=1000,
valid_sets=[dtrain, dvalid], valid_names=["train", "valid"],
callbacks=[
lgb.early_stopping(stopping_rounds=50, verbose=False),
lgb.record_evaluation(evals),
],
)
native_prob = native.predict(x_test, num_iteration=native.best_iteration)
print(f"best iteration = {native.best_iteration}")
print(f"test ROC AUC = {roc_auc_score(y_test, native_prob):.3f}")
best iteration = 106
test ROC AUC = 0.899

With the same parameters and seed, the native run stops at the same round as the scikit-learn model above. record_evaluation fills evals with the metric for every round, which lgb.plot_metric draws.

fig, ax = plt.subplots(figsize=(6, 3.8))
lgb.plot_metric(evals, metric="binary_logloss", grid=False, ax=ax)
ax.axvline(native.best_iteration, color="grey", linestyle="--",
label=f"best iteration ({native.best_iteration})")
ax.legend(frameon=False)
ax.set(title="LightGBM learning curve", xlabel="boosting round",
ylabel="log loss")
fig.tight_layout()
fig.savefig("outputs/lightgbm-learning-curve.png", dpi=150)
plt.close(fig)

Learning curve over about 156 boosting rounds. Training log loss falls from about 0.67 to about 0.07. Validation log loss falls to its minimum, about 0.42, at round 106, which a dashed line marks, then rises slightly to about 0.44.

lgb.cv returns a dictionary of per-round means and standard deviations, trimmed to the best round when early stopping is on. The keys carry a valid prefix in LightGBM 4.7; older code reads binary_logloss-mean.

cv_results = lgb.cv(
params, dtrain, num_boost_round=1000, nfold=5, stratified=True,
seed=42,
callbacks=[lgb.early_stopping(stopping_rounds=50, verbose=False)],
)
cv_mean = cv_results["valid binary_logloss-mean"]
cv_sd = cv_results["valid binary_logloss-stdv"]
print(f"keys: {list(cv_results)}")
print(f"best round = {len(cv_mean)}")
print(f"CV log loss = {cv_mean[-1]:.4f} +/- {cv_sd[-1]:.4f}")
keys: ['valid binary_logloss-mean', 'valid binary_logloss-stdv']
best round = 113
CV log loss = 0.4900 +/- 0.0293

class_weight="balanced" weights each class by the inverse of its frequency. For a binary outcome, the native parameters is_unbalance=True or scale_pos_weight do the same job. The block shifts the simulated outcome so that positives are rare. Weighting raises recall at the 0.5 cut while the ROC AUC barely moves, because the ranking of samples hardly changes. It also pushes every predicted probability up, so do not read weighted outputs as risks. When you need calibrated risks, leave the weights alone and choose the threshold on validation data.

rare = rng.binomial(1, 1 / (1 + np.exp(-(logit - 3.0))))
xr_train, xr_test, yr_train, yr_test = train_test_split(
expr, rare, test_size=0.3, stratify=rare, random_state=42
)
print(f"positive rate {rare.mean():.3f}")
for weight in [None, "balanced"]:
rare_model = lgb.LGBMClassifier(
n_estimators=200, learning_rate=0.05, num_leaves=15,
class_weight=weight, random_state=42, n_jobs=1,
deterministic=True, force_row_wise=True, verbose=-1,
)
rare_model.fit(xr_train, yr_train)
rare_prob = rare_model.predict_proba(xr_test)[:, 1]
print(f"class_weight={str(weight):>8}: "
f"ROC AUC {roc_auc_score(yr_test, rare_prob):.3f}, "
f"recall {recall_score(yr_test, rare_prob >= 0.5):.3f}, "
f"mean predicted risk {rare_prob.mean():.3f}")
print(f"observed positive rate in test: {yr_test.mean():.3f}")
positive rate 0.181
class_weight= None: ROC AUC 0.849, recall 0.296, mean predicted risk 0.116
class_weight=balanced: ROC AUC 0.847, recall 0.444, mean predicted risk 0.168
observed positive rate in test: 0.180

The regressor takes the same arguments and callbacks. The target is a continuous score built from Gene_01 and the square of Gene_02, on the same train, validation, and test rows.

score = 2.0 * expr["Gene_01"] + expr["Gene_02"] ** 2
score = score + rng.normal(scale=0.5, size=n_samples)
regressor = lgb.LGBMRegressor(
n_estimators=1000, learning_rate=0.05, num_leaves=15,
random_state=42, n_jobs=1, deterministic=True, force_row_wise=True,
verbose=-1,
)
regressor.fit(
x_train, score[x_train.index],
eval_X=(x_valid,), eval_y=(score[x_valid.index],),
eval_metric="rmse",
callbacks=[lgb.early_stopping(stopping_rounds=50, verbose=False)],
)
score_pred = regressor.predict(x_test)
score_test = score[x_test.index]
print(f"best iteration = {regressor.best_iteration_}")
print(f"test RMSE = {root_mean_squared_error(score_test, score_pred):.3f}")
print(f"test R-squared = {r2_score(score_test, score_pred):.3f}")
best iteration = 125
test RMSE = 0.795
test R-squared = 0.910

save_model writes a plain text model. Pass num_iteration to keep only the trees up to the best round.

native.save_model("outputs/lightgbm-model.txt",
num_iteration=native.best_iteration)
reloaded = lgb.Booster(model_file="outputs/lightgbm-model.txt")
same = np.allclose(reloaded.predict(x_test), native_prob)
print(f"trees in the saved model = {reloaded.num_trees()}")
print(f"same test probabilities: {same}")
trees in the saved model = 106
same test probabilities: True
scikit-learn name Native name What it controls Default
n_estimators num_iterations maximum boosting rounds 100
learning_rate learning_rate shrinkage applied to each tree 0.1
num_leaves num_leaves leaves per tree, the main complexity knob 31
max_depth max_depth depth limit, -1 for none -1
min_child_samples min_data_in_leaf minimum rows in a leaf 20
subsample bagging_fraction fraction of rows per round 1.0
subsample_freq bagging_freq bag every k rounds, 0 turns bagging off 0
colsample_bytree feature_fraction fraction of features per tree 1.0
reg_alpha lambda_l1 L1 penalty on leaf values 0.0
reg_lambda lambda_l2 L2 penalty on leaf values 0.0
n_jobs num_threads threads; 1 for a repeatable run physical cores

Tune num_leaves first, since a leaf-wise tree with many leaves overfits a small table fast. Raise min_child_samples on small cohorts. Lower learning_rate and let early stopping find the number of rounds.

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

  • LightGBM Python introduction

    The guide explains Dataset construction, validation references, training, callbacks, and model persistence. Its native examples help connect the classifier wrapper with lgb.train and lgb.cv.