保存sklearn分类器交叉匹配_

2024-04-20 03:47:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个分类器,我正在使用一个交叉值进行拟合,得到了很好的结果。基本上我所做的就是:

clf = RandomForestClassifier(class_weight="balanced")
scores = cross_val_score(clf, data, target, cv=8)
predict_RF = cross_val_predict(clf, data, target, cv=8)

from sklearn.externals import joblib
joblib.dump(clf, 'churnModel.pkl')

基本上,我想做的是把这个模型通过交叉值拟合,然后导出到joblib。然而,当我试图把它放在一个单独的项目中时,我得到了:

^{pr2}$

所以我猜cross_-val实际上并没有把它保存到我的clf中?如何保持cross_-val生成的模型拟合度?在


Tags: 模型targetdata分类器valpredict交叉cv
1条回答
网友
1楼 · 发布于 2024-04-20 03:47:52

在胡安帕.阿里维拉加是对的。恐怕你得手工操作,但scikit learn使它变得非常容易。cross_val_分数可创建未返回给您的经过培训的模型。下面列出的是经过培训的模型(即clf_模型)

from sklearn.model_selection import StratifiedKFold
from sklearn.ensemble import RandomForestClassifier
from copy import deepcopy

kf = StratifiedKFold(n_splits=8)
clf = RandomForestClassifier(class_weight="balanced")
clf_models = []

# keep in mind your X and y should be indexed same here
kf.get_n_splits(X_data)
for train_index, test_index in kf.split(X_data):
    print("TRAIN:", train_index, "TEST:", test_index)
    X_train, X_test = X_data[train_index], X_data[test_index]
    y_train, y_test = y_data[train_index], y_data[test_index]
    tmp_clf = deepcopy(clf)
    tmp_clf.fit(X_train, y_train)

    print("Got a score of {}".format(tmp_clf.score(X_test, y_test))
    clf_models.append(tmp_clf)

-通过编辑胡安帕.阿里维拉加的建议 层状褶皱是一个更好的选择。只是为了示范。在

相关问题 更多 >