在R中,在运行“随机森林”模型之后,我可以使用save.image("***.RData")
来存储模型。然后,我可以直接加载模型来进行预测。
你能在python中做类似的事情吗?我将模型和预测分成两个文件。在模型文件中:
rf= RandomForestRegressor(n_estimators=250, max_features=9,compute_importances=True)
fit= rf.fit(Predx, Predy)
我尝试返回rf
或fit
,但仍然无法加载预测文件中的模型。
你能使用sklearn随机森林包来分离模型和预测吗?
发布于 2013-12-19 00:09:19
...
import cPickle
rf = RandomForestRegresor()
rf.fit(X, y)
with open('path/to/file', 'wb') as f:
cPickle.dump(rf, f)
# in your prediction file
with open('path/to/file', 'rb') as f:
rf = cPickle.load(f)
preds = rf.predict(new_X)
发布于 2020-06-24 22:42:48
您可以使用joblib
来保存和加载来自scikit learn的随机森林(实际上,来自scikit learn的任何模型)
示例:
import joblib
from sklearn.ensemble import RandomForestClassifier
# create RF
rf = RandomForestClassifier()
# fit on some data
rf.fit(X, y)
# save
joblib.dump(rf, "my_random_forest.joblib")
# load
loaded_rf = joblib.load("my_random_forest.joblib")
更重要的是,joblib.dump
has compress
参数,因此模型可以压缩。我在虹膜数据集上做了非常简单的test,compress=3
将文件的大小减少了大约5.6倍。
发布于 2016-03-21 00:16:30
我使用dill,它存储所有的数据,我想可能是模块信息?也许不是。我记得我曾尝试使用pickle
来存储这些非常复杂的对象,但它对我不起作用。cPickle
可能和dill
做同样的事情,但是我从来没有尝试过cpickle
。看起来它的工作原理与此完全相同。我使用了"obj“扩展名,但这并不意味着conventional...It对我来说是有意义的,因为我是在存储对象。
import dill
wd = "/whatever/you/want/your/working/directory/to/be/"
rf= RandomForestRegressor(n_estimators=250, max_features=9,compute_importances=True)
rf.fit(Predx, Predy)
dill.dump(rf, open(wd + "filename.obj","wb"))
顺便说一句,不确定你是否使用iPython,但有时用这种方式写一个文件不会,所以你必须这样做:
with open(wd + "filename.obj","wb") as f:
dill.dump(rf,f)
再次调用对象:
model = dill.load(open(wd + "filename.obj","rb"))
https://stackoverflow.com/questions/20662023
复制相似问题