python - 将随机森林模型保存到文件?

标签 python scikit-learn save pickle random-forest

正在尝试保存随机森林模型。

所有的方法都失败了:

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 的问题……因为现在我正在更仔细地测试它……有时它可以工作!!

可能是自动重载问题!!

Yep the moment I modify the source code save_model() stops working ..

最佳答案

使用 joblib 来 pickle 你训练好的模型:

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(...)

更新:

根据这个错误,你必须使用更高的协议(protocol)进行 pickeling (>= 2):

dill : ValueError: pickle protocol must be <= 2

尝试使用更高的协议(protocol)进行转储,如下所示:

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

关于python - 将随机森林模型保存到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57939025/

相关文章:

python - 如何获得决策树的ROC曲线?

java - 如何在 Java 中修改 HTML 文件并保存更改

python - 当在前一个循环中找到某个字符时,如何开始新的循环?

python - 在 OpenCV 中跳过帧并寻找 RTSP 流的结尾

python - 如何跟随 Django 中的按钮单击?

machine-learning - 为什么不能从宏精度和召回率计算宏 F1 度量?

python ,scikits-学习 : which learning methods support sparse feature vectors?

matrix - Julia:如何修改已保存为二进制文件的矩阵的列?

android - Qt API 获取应用程序用户数据在 iOS 和 Android 上的保存位置

Python 命令行 args 格式问题