首页 > 解决方案 > 将随机森林模型保存到文件?

问题描述

试图保存随机森林模型。

所有方法都失败了:

self.model = RandomForestClassifier(n_estimators=n_estimators,criterion='entropy', min_samples_leaf=2, max_depth=15,min_samples_split=5, max_features=None, n_jobs=-1, random_state=555)

def save_model(self, fname):
    with open(fname,'wb') as f :
        dill.dumps(self.model, f)



pickle: TypeError: can't pickle instancemethod objects

joblib : PicklingError: Can't pickle <type 'instancemethod'>: it's not found as __builtin__.instancemethod

cPickle : TypeError: can't pickle instancemethod objects

dill : ValueError: pickle protocol must be <= 2

 : type(r.model)
 : sklearn.ensemble.forest.RandomForestClassifier

 :with open('test.dill', 'wb') as f : dill.dump(r.model,f, protocol=2)

  PicklingError: Can't pickle <class 'random_forest.RFWords'>: it's not the same object as random_forest.RFWords

random_forest.RFWords 是包含 RF 的类!它如何访问 self.model 所在的类


嗯......我认为这是 IPython 问题......因为现在我正在更周到地测试它......有时它可以工作!

可能是自动重装问题!!

是的,当我修改源代码时 save_model() 停止工作..

标签: pythonscikit-learnsavepicklerandom-forest

解决方案


使用 joblib 腌制你训练好的模型:

from joblib import dump, load
from sklearn.ensemble import RandomForestClassifier

#load data
X, y = load_data(...)

#fit the model
estimator = RandomForestClassifier()
estimator.fit(X,y)

#pickle model to disk
dump(estimator, 'my_randomforest_model.joblib') 

#loading saved model
estimator = load('my_randomforest_model.joblib')

estimator.predict(...)

更新:

根据此错误,您必须使用更高的协议进行腌制(> = 2):

dill : ValueError: pickle 协议必须 <= 2

尝试使用更高的协议转储如下:

dump(estimator, 'my_randomforest_model.joblib', protocol=2) 

推荐阅读