Sub topic 8
Training LightGBM with the sklearn and native APIs
This chapter assumes you know Python and pandas, the difference between training and validation data, and metrics such as RMSE and AUC. It also assumes you have read the earlier chapters on early stopping and LightGBM's key parameters. Here you will train models with both of LightGBM's Python interfaces and learn which errors to expect.
Two interfaces, one engine
LightGBM ships two Python interfaces over the same C++ core.
- The scikit-learn API (
LGBMRegressor,LGBMClassifier,LGBMRanker) follows thefitandpredictconvention. It works inside pipelines,cross_val_scoreand grid searches. - The native API (
lgb.Dataset,lgb.train,lgb.cv) takes a parameter dictionary and returns aBooster. It exposes the dataset object directly, which gives you more control over binning, reuse and memory.
Both produce a Booster in the end. The sklearn wrapper keeps it in model.booster_.
| Concern | sklearn API | Native API |
|---|---|---|
| Entry point | `LGBMRegressor.fit(X, y)` | `lgb.train(params, Dataset)` |
| Number of trees | `n_estimators` | `num_boost_round` |
| Learning rate | `learning_rate` | `learning_rate` (in `params`) |
| Validation data | `eval_set=[(X, y)]` | `valid_sets=[Dataset]` |
| Best round after early stopping | `best_iteration_` | `best_iteration` |
| Built-in cross-validation | use scikit-learn tools | `lgb.cv` |
LightGBM accepts many parameter aliases, such as num_leaves and num_leaf, and n_estimators and num_boost_round. If you pass two aliases for the same setting, one silently wins and LightGBM prints a warning. Pick one name and use it consistently.
Training with the sklearn API
The example below trains a regressor on the California housing data. It sets a high n_estimators and lets early stopping choose 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_)Several details matter here.
- Early stopping is a callback in current LightGBM versions. Older code passed
early_stopping_rounds=tofit. That argument was removed in LightGBM 4.0, so uselgb.early_stopping. lgb.log_evaluation(100)prints the metric every 100 rounds. Without it, training is silent.best_iteration_holds the round with the best validation score.predictuses it by default, so you do not need to slice the model yourself.eval_metric="rmse"adds a metric on top of the default for the objective. With several metrics, early stopping watches the first one by default. It also watches every validation set unless you setfirst_metric_only=True.
Training with the native API
The native API separates data from parameters. You wrap each table in a Dataset, then pass a plain dictionary of parameters to lgb.train. The next example uses pandas category columns, which LightGBM detects and treats as categorical features automatically.
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)Points to check in this code:
reference=train_setmakes the validationDatasetreuse the training set's bin boundaries and category mappings. Without it, the two sets could be binned differently, and the validation scores would be wrong or the call would fail.bagging_fractionhas no effect unlessbagging_freqis at least 1. This is a common silent mistake. Herebagging_freq=1resamples rows at every iteration.feature_fraction=0.8samples 80% of the columns for each tree. Both sampling settings add randomness that reduces overfitting.- The training metric does not appear unless you add the training set to
valid_sets. Add it only when you want to compare train and validation curves. lgb.trainreturns aBooster. Callbooster.predict(X_valid)for probabilities from abinaryobjective. The sklearn classifier'spredictreturns class labels andpredict_probareturns probabilities.
How the two APIs relate
The diagram shows where each interface hands off to the shared core.
Because the sklearn wrapper builds the Dataset for you on every fit call, repeated fits on the same data pay the binning cost each time. With the native API you can build a Dataset once and reuse it across parameter trials. This saves time on large tables.
Reading the training log
With log_evaluation(100), the output looks like this for a regressor:
Training until validation scores don't improve for 50 rounds
[100] valid_0's rmse: 0.52 valid_0's l2: 0.27
[200] valid_0's rmse: 0.48 valid_0's l2: 0.23
Early stopping, best iteration is:
[240] valid_0's rmse: 0.47 valid_0's l2: 0.22The name valid_0 is the first validation set. The model stopped at round 290 because the best round was 240 and 50 more rounds brought no improvement. LightGBM keeps all trees trained, but predict uses only the first 240.
Saving, loading and predicting
Save a model as text so another process can load it without pickling.
booster.save_model("model.txt", num_iteration=booster.best_iteration)
loaded = lgb.Booster(model_file="model.txt")
probabilities = loaded.predict(X_valid)
print(probabilities[:5])The saved file stores the category mapping seen at training time as part of the model. At prediction time, pass the same columns in the same order, and keep the category columns as category dtype with matching levels. A mismatch in feature names or counts raises an error. A mismatch in category levels can give wrong predictions without any error.
Common errors
- Calling
fitwithearly_stopping_rounds=fails on LightGBM 4 and later. Use the callback. - Using the test set as
eval_setfor early stopping leaks information. Early stopping picks the round that scores best on that data, so the score is optimistic. Keep a separate final test set. - Setting
n_estimatorslow and expecting early stopping to help. Early stopping can only stop sooner. Give it room, with a low learning rate and a high round limit. - Passing object-dtype string columns. LightGBM rejects them. Convert to
categoryor encode them first. - Forgetting
reference=on validationDatasetobjects in the native API.
Exercise
You train with lgb.train, numboostround=1000 and lgb.early_stopping(50). The log says the best iteration is 312. How many trees did LightGBM train, and which trees does booster.predict use by default?
Show answer
It trained 362 trees, because it stopped 50 rounds after the best one. By default predict uses the first 312 trees, the best iteration.
Exercise
A native-API run uses bagging_fraction=0.7 but the results are identical to a run without it. What is the likely cause, and what is the fix?
Show answer
baggingfreq defaults to 0, which disables bagging, so baggingfraction is ignored. Set bagging_freq to 1 or higher.