python - 将随机森林模型保存到文件?
问题描述
试图保存随机森林模型。
所有方法都失败了:
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() 停止工作..
解决方案
使用 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)
推荐阅读
- javascript - Laravel:如何在 JS 刀片循环中使用“d”JS 函数变量?
- html - 如何在Angular中的Html中动态对齐Grid tile容器中的文本
- javascript - jQuery:滚动过去 div 时添加/删除样式
- css - 如何设置 HTML 5 音频播放器的样式,使其始终以“悬停”状态显示进度条?
- c# - 将数组分配给对象?
- amazon-web-services - DynamoDB 单项性能
- reactjs - 为什么在 React App 中使用 useHistory goBack 函数而不是窗口历史返回函数?
- javascript - React Native FlatList 使应用程序在 10 个元素后变得异常缓慢
- c - Azure 设备孪生 - HTTP 或 MQTT
- javascript - React Js 如何检测当前操作系统