How to save to disk / export a lightgbm LGBMRegressor model trained in python?

Question:

Hi I am unable to find a way to save a lightgbm.LGBMRegressor model to a file for later re-use.

Asked By: Utpal Datta

||

Answers:

Try:

my_model.booster_.save_model('mode.txt')
#load from model:

bst = lgb.Booster(model_file='mode.txt')

Note: the API state that

bst = lgb.train(…)
bst.save_model('model.txt', num_iteration=bst.best_iteration)

Depending on the version, one of the above works. For generic, You can also use pickle or something similar to freeze your model.

import joblib
# save model
joblib.dump(my_model, 'lgb.pkl')
# load model
gbm_pickle = joblib.load('lgb.pkl')

Let me know if that helps

Answered By: Prayson W. Daniel

With the lastest version of lightGBM using import lightgbm as lgb, here is how to do it:

model.save_model('lgb_classifier.txt', num_iteration=model.best_iteration) 

and then you can read the model as follow :

model = lgb.Booster(model_file='lgb_classifier.txt')
Answered By: smerllo
clf.save_model('lgbm_model.mdl')
clf = lgb.Booster(model_file='lgbm_model.mdl')
Answered By: amalik2205

For Python 3.7 and lightgbm==2.3.1, I found that the previous answers were insufficient to correctly save and load a model. The following worked:

lgbr = lightgbm.LGBMRegressor(num_estimators = 200, max_depth=5)
lgbr.fit(train[num_columns], train["prep_time_seconds"])
preds = lgbr.predict(predict[num_columns])
lgbr.booster_.save_model('lgbr_base.txt')

Finally, we can validated that this worked via:

model = lightgbm.Booster(model_file='lgbr_base.txt')
model.predict(predict[num_columns])

Without the above, I was getting the error: AttributeError: 'LGBMRegressor' object has no attribute 'save_model'

Answered By: JFRANCK