Posts Applying early_stopping in LightGBM
Post
Cancel

Applying early_stopping in LightGBM

LightGBM Logo

Applying early_stopping in LightGBM

When using LightGBM, attempting to pass early_stopping_rounds directly to the train() function may result in the following error:

TypeError: train() got an unexpected keyword argument 'early_stopping_rounds'

To resolve this issue, you should use the early_stopping callback instead.

❌ Incorrect Code (Error Occurs)

1
2
3
import lightgbm as lgb

lgb_model = lgb.train(params, lgb_train, valid_sets=[lgb_test], early_stopping_rounds=10)

Executing this code will raise a TypeError.

✅ Correct Code (Using Callbacks for Early Stopping)

1
2
3
4
5
6
7
8
import lightgbm as lgb
from lightgbm import early_stopping

callbacks = [early_stopping(stopping_rounds=50)]

# Train LightGBM model
lgb_model = lgb.train(params, lgb_train, valid_sets=[lgb_test], 
                      num_boost_round=100, callbacks=callbacks)

🔹 Key Changes

  • Instead of passing early_stopping_rounds directly to train(), use the early_stopping callback.
  • Add early_stopping(stopping_rounds=50) to the callbacks list and pass it as an argument to train().

With this approach, early stopping is correctly applied in LightGBM!