opening old xgboost pickles with the new xgboost version 'XGBClassifier' object has no attribute 'kwargs'

折月煮酒 提交于 2020-02-06 18:53:33

问题


I was using xgboost version 0.6 when I pickled some pickle objects. Now I upgraded to version 0.82 and when I'm trying to unpickle the old models I get:

AttributeError: 'XGBClassifier' object has no attribute 'kwargs'

I would really like to use these model without re training them, is there any way to open these pickles?


回答1:


The new xgboost requires that objects will have a "kwargs" attribute, which old models do not have. One way to solve this is to downgrade to the old xgboost version, open them, add to each model the model.kwargs=None and then save them again, they should now work...

Another workaround is to hack the pickle file. You will load the pickle as a string, add the needed attribute and then load the pickle:

import re
xg_str = open('path_to_old_model.pkl').read()
kwargs_value= "kwargs'\np8\nNsS'"
new_xgboost = re.sub('colsample_bylevel', kwargs_value+"""colsample_bylevel""", xg_str)
new_model = pkl.loads(new_xgboost)

this adds "None" as the self.kwargs for your models. regex finds where the object attributes are declared, by searching for a known attribute in the model, "colsample_bylevel" and then adds before it another attribute.

To see how pickle encodes attributes you can create any class with some attributes and apply pkl.dumps to an instance. if it's a short class it will be pretty easy to read, that's how I got that "kwargs'\np8\nNsS'" means "kwargs=None".

Worked for me! I'm sure this can help with similar backwards compatibility issues with pickles, not neccesarily with this specific attribute.



来源:https://stackoverflow.com/questions/56755507/opening-old-xgboost-pickles-with-the-new-xgboost-version-xgbclassifier-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!