Online predictions with LIME (or how to pickle an Explainer object?)
Hi,
I'm considering deploying LIME in a production environment; say, the user inputs the relevant columns and some server is listening and using LIME to return LIME explanations.
I'm not sure how to go about this, but I thought the best way would be to somehow pickle the Explainer object, that then could be read on demand and then feed it with the user input. Would something like that work? Not sure if it would still require LIME and sci-kit learn to be installed and loaded each time.
The official LIME implementation depends on anonymous functions (i.e. lambdas). Those can't be pickled. But there are other python packages that allow you to do that.
See #126 and #98 on pickling the explainer. You would still need sklearn to be installed if you just use the code as is, because of lines like this one, but you could probably just pickle the needed functions if you can't assume sklearn is installed.
@marcotcr I think this thread might be a good place to ask you this: is there a specific engineering reason to use lambdas in your code? I know it makes stuff prettier (IMHO, at least) but we will end up with issues when using packages like joblib.
No, no reason. I think the only place we store lambda functions is here, and they could easily be removed from there.
Late contribution to the discussion, but it might be useful for users with the same problem in the future: @echo66 , https://github.com/uqfoundation/dill can be used for pickling code with lambda functions to avoid the joblib limitation.
@auwalsoe it is not so easy, AFAIK. The joblib library uses pickle, not dill.
Same issue here. Can't pickle or save with joblib.
Dill is working well, for me in the context of the OP's question.
To save:
import dill
with open(explainer_filename, 'wb') as f: dill.dump(explainer, f)
To load:
with open(explainer_filename, 'rb') as f: explainer = dill.load(f)
dill is pickling and unpickling the lime explainer. But when i use explain_instance, it is failing with error as below.
exp = explainer.explain_instance(data.values[i], loaded_model.predict_proba, num_features=5, top_labels=1)
unknown opcode File "/usr/local/lib/python3.6/site-packages/lime/lime_tabular.py", line 311, in explain_instance
data, inverse = self.__data_inverse(data_row, num_samples)
File "/usr/local/lib/python3.6/site-packages/lime/lime_tabular.py", line 464, in __data_inverse
first_row = self.discretizer.discretize(data_row)
File "/usr/local/lib/python3.6/site-packages/lime/discretize.py", line 109, in discretize
ret[feature] = int(self.lambdas[feature](ret[feature]))
File "C:\Users\user1\AppData\Local\Continuum\anaconda3\lib\site-packages\lime\discretize.py", line 60, in <lambda>
for feature, qts in zip(self.to_discretize, bins):
SystemError: