Sub topic 8
Training LightGBM with the sklearn and native APIs
This chapter assumes you know Python and pandas, train/validation splits, and metrics such as RMSE and AUC. You should also know why early stopping is used and what num_leaves controls, both covered in earlier chapters.
LightGBM offers two ways to train. The scikit-learn API (LGBMRegressor, LGBMClassifier) fits into pipelines and cross-validation tools. The native API (lgb.Dataset and lgb.train) gives more control and exposes the library's own parameter names. Both run the same training code underneath.
The scikit-learn API
The estimator takes hyperparameters in its constructor and trains with fit. Set n_estimators high and let early stopping pick the real number of trees.
import lightgbm as lgb
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
X, y = fetch_california_housing(return_X_y=True, as_frame=True)
X_train, X_valid, y_train, y_valid = train_test_split(
X, y, test_size=0.2, random_state=0
)
model = lgb.LGBMRegressor(n_estimators=2000, learning_rate=0.05, num_leaves=31)
model.fit(
X_train,
y_train,
eval_set=[(X_valid, y_valid)],
eval_metric="rmse",
callbacks=[lgb.early_stopping(stopping_rounds=50), lgb.log_evaluation(100)],
)
print(model.best_iteration_)Early stopping and logging are callbacks. The older early_stopping_rounds argument to fit was removed in LightGBM 4, so use lgb.early_stopping(...). After training, predict uses best_iteration_ by default.
The native API
The native API wraps data in a Dataset, which also holds the histogram bins. Parameters go in a dictionary.
import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 5000
df = pd.DataFrame({
"age": rng.integers(18, 70, n),
"city": pd.Categorical(rng.choice(["A", "B", "C", "D"], n)),
"plan": pd.Categorical(rng.choice(["free", "basic", "pro"], n)),
})
signal = (df["plan"] == "pro") | (df["age"] > 55)
flip = rng.random(n) < 0.1
y = (signal ^ flip).astype(int)
X_train, X_valid, y_train, y_valid = train_test_split(
df, y, test_size=0.2, random_state=0
)
train_set = lgb.Dataset(X_train, label=y_train)
valid_set = lgb.Dataset(X_valid, label=y_valid, reference=train_set)
params = {
"objective": "binary",
"metric": "auc",
"learning_rate": 0.05,
"num_leaves": 31,
"min_data_in_leaf": 20,
"feature_fraction": 0.8,
"bagging_fraction": 0.8,
"bagging_freq": 1,
"verbose": -1,
}
booster = lgb.train(
params,
train_set,
num_boost_round=1000,
valid_sets=[valid_set],
callbacks=[lgb.early_stopping(50)],
)
print(booster.best_iteration)Three details matter here:
reference=train_setmakes the validation set reuse the training bin boundaries. Without it, the two sets could be binned differently.- Pandas
categorycolumns are treated as categorical features automatically. bagging_fractionhas no effect unlessbagging_freqis greater than 0.
Choosing between the APIs
| Need | Better choice |
|---|---|
| `GridSearchCV`, `Pipeline`, `cross_val_score` | scikit-learn API |
| Reusing one `Dataset` across many runs | Native API |
| Custom objectives or fine control of the loop | Native API |
| Familiar `fit`/`predict` interface | scikit-learn API |
Exercise
In the native example, you remove reference=train_set from the validation Dataset. What can go wrong, and why?
Show answer
The validation set may be binned with its own boundaries instead of the training set's. The trees were built on the training bins, so validation scores would then be computed on inconsistent feature values and can be wrong. Passing reference=train_set makes both sets share the same bins.
Exercise
You call lgb.train with bagging_fraction set to 0.8 but leave bagging_freq at its default. Does row subsampling happen?
Show answer
No. Bagging is only active when bagging_freq is greater than 0, so all rows are used in every round.