Skip to content
Advertisement

Python: How to retrive the best model from Optuna LightGBM study?

I would like to get the best model to use later in the notebook to predict using a different test batch.

reproducible example (taken from Optuna Github) :

JavaScript

my understanding is that the study below will tune for accuracy. I would like to somehow retrieve the best model from the study (not just the parameters) without saving it as a pickle, I just want to use the model somewhere else in my notebook.

JavaScript

desired output would be

JavaScript

Advertisement

Answer

I think you can use the callback argument of Study.optimize to save the best model. In the following code example, the callback checks if a given trial is corresponding to the best trial and saves the model as a global variable best_booster.

JavaScript

If you define your objective function as a class, you can remove the global variables. I created a notebook as a code example. Please take a look at it: https://colab.research.google.com/drive/1ssjXp74bJ8bCAbvXFOC4EIycBto_ONp_?usp=sharing

I would like to somehow retrieve the best model from the study (not just the parameters) without saving it as a pickle

FYI, if you can pickle the boosters, I think you can make the code simple by following this FAQ.

Advertisement