# XGBoost vs LightGBM in Python: A Quick Start for Both

> XGBoost vs LightGBM in Python with XGBClassifier and LGBMClassifier: early stopping, categorical columns, num_leaves vs max_depth, feature importance, and fit time.

Source: https://www.pythoncharts.com/machine-learning/xgboost-vs-lightgbm-python/ | Published: 2026-11-26 | Author: Alex Scott | Category: Machine Learning | Tags: machine learning, xgboost, lightgbm, gradient boosting, classification, scikit-learn, matplotlib

XGBoost and LightGBM are both gradient boosting libraries with a scikit-learn style interface: use `XGBClassifier()` or `LGBMClassifier()`, then call `fit()` and `predict_proba()`. On most tabular data their accuracy is close, so the practical differences are how each grows trees, what the settings are called, and how fast they run on your data.

Install them with `pip install xgboost lightgbm`. On macOS both need the OpenMP library, installed with `brew install libomp`. The code here was run with XGBoost 3.4 and LightGBM 4.7.

## Quick Example

This example makes up 40,000 hotel bookings and predicts which ones get canceled. Both models stop adding trees once the validation log loss hasn't improved for 50 rounds.

```python
import lightgbm as lgb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from lightgbm import LGBMClassifier
from sklearn.metrics import log_loss, roc_auc_score
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier

rng = np.random.default_rng(73)
n = 40_000
bookings = pd.DataFrame({
    "lead_time": rng.gamma(1.6, 45, n).round(),
    "nightly_rate": rng.lognormal(np.log(140), 0.3, n).round(),
    "nights": rng.integers(1, 10, n),
    "previous_stays": rng.poisson(0.6, n),
    "channel": pd.Categorical(rng.choice(
        ["direct", "online agency", "corporate", "tour operator"],
        n, p=[0.3, 0.45, 0.15, 0.1])),
    "deposit": pd.Categorical(rng.choice(
        ["none", "partial", "prepaid"], n, p=[0.65, 0.2, 0.15])),
})
bookings.loc[rng.random(n) < 0.12, "previous_stays"] = np.nan
log_odds = (
    -1.5 + 0.9 * np.log1p(bookings.lead_time / 60)
    + 0.9 * (bookings.channel == "online agency")
    - 0.6 * (bookings.channel == "corporate")
    - 2.0 * (bookings.deposit == "prepaid")
    - 0.8 * (bookings.deposit == "partial")
    - 0.5 * bookings.previous_stays.fillna(0).clip(0, 3)
    + 1.1 * ((bookings.nightly_rate > 180) & (bookings.lead_time > 90))
    + rng.normal(0, 0.5, n))
canceled = rng.binomial(1, 1 / (1 + np.exp(-log_odds)))

X_rest, X_test, y_rest, y_test = train_test_split(
    bookings, canceled, test_size=0.2, stratify=canceled, random_state=73)
X_train, X_valid, y_train, y_valid = train_test_split(
    X_rest, y_rest, test_size=0.2, stratify=y_rest, random_state=73)

xgb_model = XGBClassifier(
    n_estimators=2000, learning_rate=0.05, early_stopping_rounds=50,
    eval_metric="logloss", n_jobs=4, random_state=73)
xgb_model.fit(X_train, y_train, eval_set=[(X_valid, y_valid)], verbose=False)

lgbm_model = LGBMClassifier(
    n_estimators=2000, learning_rate=0.05, n_jobs=4, random_state=73,
    verbose=-1)
lgbm_model.fit(
    X_train, y_train, eval_X=X_valid, eval_y=y_valid,
    eval_metric="binary_logloss",
    callbacks=[lgb.early_stopping(50, verbose=False)])

for name, model in [("XGBoost", xgb_model), ("LightGBM", lgbm_model)]:
    p = model.predict_proba(X_test)[:, 1]
    print(f"{name}: AUC {roc_auc_score(y_test, p):.4f}, "
          f"log loss {log_loss(y_test, p):.4f}")

curves = {
    "XGBoost": (xgb_model.evals_result()["validation_0"]["logloss"],
                xgb_model.best_iteration + 1, "#2563eb"),
    "LightGBM": (lgbm_model.evals_result_["valid_0"]["binary_logloss"],
                 lgbm_model.best_iteration_, "#16a34a"),
}
fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
for name, (loss, best, color) in curves.items():
    ax.plot(range(1, len(loss) + 1), loss, color=color, lw=2,
            label=f"{name} (best at {best} trees)")
    ax.plot(best, loss[best - 1], "o", color=color, ms=8)
ax.set(title="Validation log loss during training", xlabel="Number of trees",
       ylabel="Log loss", ylim=(0.51, 0.60))
ax.legend()
plt.show()
```

![Validation log loss of XGBoost and LightGBM falling quickly, bottoming out between 70 and 90 trees, then rising slightly](https://www.pythoncharts.com/machine-learning/xgboost-vs-lightgbm-python/images/xgboost-vs-lightgbm-quick-example.png)

The two curves are close, and both stop early: XGBoost's best round is 75 trees and LightGBM's is 81, far below the limit of 2,000. On the test set LightGBM scores an AUC of 0.7333 and XGBoost 0.7313. A gap that small on 8,000 rows can easily flip with a different split.

## Early Stopping in XGBoost and LightGBM

The two libraries set up early stopping differently:

| | XGBoost | LightGBM |
|---|---|---|
| Where to set it | `early_stopping_rounds=50` in the constructor | `callbacks=[lgb.early_stopping(50)]` in `fit()` |
| Validation data | `eval_set=[(X_valid, y_valid)]` | `eval_X=X_valid, eval_y=y_valid` |
| Best round | `best_iteration` (counts from 0) | `best_iteration_` (counts from 1) |
| History | `evals_result()` | `evals_result_` |

LightGBM 4.7 added `eval_X` and `eval_y` and deprecated `eval_set`. On older versions, pass `eval_set=[(X_valid, y_valid)]`.

After early stopping, `predict()` and `predict_proba()` use the best round automatically. Keep a separate test set, as above, because the validation set helped choose the model. More on that in [train/test splits and cross-validation](https://www.pythoncharts.com/machine-learning/train-test-split-cross-validation-python/).

## num_leaves vs max_depth: How Each Library Grows Trees

XGBoost grows trees level by level by default and limits them with `max_depth` (default 6). LightGBM grows whichever leaf reduces the loss most and limits trees with `num_leaves` (default 31). That makes LightGBM trees lopsided and its main complexity setting different.

```python
def best_loss(model):
    if isinstance(model, XGBClassifier):
        model.fit(X_train, y_train, eval_set=[(X_valid, y_valid)],
                  verbose=False)
    else:
        model.fit(X_train, y_train, eval_X=X_valid, eval_y=y_valid,
                  callbacks=[lgb.early_stopping(50, verbose=False)])
    return log_loss(y_valid, model.predict_proba(X_valid)[:, 1])

depths = [1, 2, 3, 4, 6, 8, 10]
leaves = [2, 4, 8, 16, 31, 63, 127]
xgb_losses = [best_loss(XGBClassifier(**{**xgb_model.get_params(), "max_depth": d}))
              for d in depths]
lgbm_losses = [best_loss(LGBMClassifier(**{**lgbm_model.get_params(), "num_leaves": k}))
               for k in leaves]

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4.2), sharey=True,
                               layout="constrained")
ax1.plot(depths, xgb_losses, "o-", color="#2563eb", lw=2)
ax1.set(title="XGBoost", xlabel="max_depth", ylabel="Best validation log loss")
ax2.plot(leaves, lgbm_losses, "o-", color="#16a34a", lw=2)
ax2.set(title="LightGBM", xlabel="num_leaves", xscale="log")
ax2.set_xticks(leaves, labels=leaves)
ax2.minorticks_off()
plt.show()
```

![Two line charts of best validation log loss against XGBoost max_depth and LightGBM num_leaves, with small trees scoring best and large trees worse](https://www.pythoncharts.com/machine-learning/xgboost-vs-lightgbm-python/images/xgboost-vs-lightgbm-tree-size.png)

Small trees do best on this data. A depth of 2 and a limit of 4 leaves both reach a log loss of 0.5171, compared with 0.5223 at XGBoost's default depth of 6 and 0.5198 at LightGBM's default of 31 leaves. Data with stronger interactions between columns will favor bigger trees, so search this setting.

When you move settings between the libraries, a tree of depth `d` has at most `2**d` leaves. Copying `max_depth=6` over as `num_leaves=64` allows much deeper, narrower branches than XGBoost would build.

## Categorical Columns and Missing Values

Both models above took the data with no encoding and no imputation:

- **Categories:** convert text columns to the pandas `category` dtype. LightGBM detects them, and so does XGBoost 3.4, where `enable_categorical` defaults to `True`. Older XGBoost versions (3.0, for example) need `XGBClassifier(enable_categorical=True)`.
- **Missing values:** both learn which side of each split `NaN` should go to.

Predict with a DataFrame that has the same columns and dtypes as the training data.

## Compare Feature Importance

The default `feature_importances_` values aren't comparable: LightGBM counts the splits that use each feature, while XGBoost reports the average gain per split. Ask both for total gain and convert to shares.

```python
gain = pd.DataFrame({
    "XGBoost": pd.Series(
        xgb_model.get_booster().get_score(importance_type="total_gain")),
    "LightGBM": pd.Series(
        lgbm_model.booster_.feature_importance(importance_type="gain"),
        index=lgbm_model.feature_name_),
}).fillna(0)
gain = (gain / gain.sum() * 100).sort_values("XGBoost")
splits = pd.Series(lgbm_model.feature_importances_,
                   index=lgbm_model.feature_name_)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4.2), sharey=True,
                               layout="constrained")
gain.plot.barh(ax=ax1, color=["#2563eb", "#16a34a"], width=0.75)
ax1.set(title="Share of total gain", xlabel="%")
ax2.barh(gain.index, splits[gain.index], color="#86efac")
ax2.set(title="LightGBM default: split count", xlabel="Splits")
plt.show()
```

![Grouped bars showing deposit and channel leading in total gain for both libraries, next to LightGBM split counts where lead time and nightly rate rank highest](https://www.pythoncharts.com/machine-learning/xgboost-vs-lightgbm-python/images/xgboost-vs-lightgbm-importance.png)

Measured by gain, the two models agree: `deposit` comes first, then `channel`. LightGBM's default split count ranks `lead_time` and `nightly_rate` on top, because numeric columns offer many places to split. For rankings you can trust more, use [permutation importance](https://www.pythoncharts.com/machine-learning/feature-importance-python/) or [SHAP plots](https://www.pythoncharts.com/machine-learning/shap-plots-python/).

## Which Is Faster, XGBoost or LightGBM?

It depends on the number of rows, columns, cores, and tree settings, so time both on your own data. This loop fits 200 trees of each:

```python
from time import perf_counter

for copies in [1, 10]:
    X_big = pd.concat([X_train] * copies, ignore_index=True)
    y_big = np.tile(y_train, copies)
    for cls in [XGBClassifier, LGBMClassifier]:
        model = cls(n_estimators=200, learning_rate=0.05, n_jobs=4)
        if cls is LGBMClassifier:
            model.set_params(verbose=-1)
        start = perf_counter()
        model.fit(X_big, y_big)
        print(f"{len(X_big):>7,} rows  {cls.__name__:<15}"
              f"{perf_counter() - start:.2f} s")
```

On an 8-core Apple silicon Mac, XGBoost took about 0.3 seconds on 25,600 rows and LightGBM about 0.6. At 256,000 rows both took between 1 and 1.3 seconds, and which one finished first changed between runs. LightGBM's reputation for speed comes mostly from larger and wider datasets than this one.

## When to Use Which

| Choose | If |
|---|---|
| XGBoost | You want depth-limited trees, or your team and serving tools already use it |
| LightGBM | Training time matters on large data and your own timing shows it ahead |
| `HistGradientBoostingClassifier` | You want to stay inside scikit-learn with no extra dependency |
| [Random forest](https://www.pythoncharts.com/machine-learning/random-forest-classifier-python/) | You want a solid result with little tuning |

## Practical Tips

- Lower `learning_rate` and let early stopping find the number of trees.
- Set `n_jobs` to the number of physical cores you want to use. More threads can be slower on a busy machine.
- Against overfitting, shrink the trees first, then try `min_child_weight` (XGBoost) or `min_child_samples` (LightGBM).
- To search several settings at once, use [Optuna](https://www.pythoncharts.com/machine-learning/optuna-hyperparameter-tuning-python/).

## Similar Topics

- [Hyperparameter Tuning with Optuna in Python](https://www.pythoncharts.com/machine-learning/optuna-hyperparameter-tuning-python/)
- [SHAP Plots in Python](https://www.pythoncharts.com/machine-learning/shap-plots-python/)
- [Random Forest Classifier in Python: A Complete Example](https://www.pythoncharts.com/machine-learning/random-forest-classifier-python/)
