我有一个使用cross_val拟合的分类器,并且取得了不错的结果。基本上我所做的就是:
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 joblibjoblib.dump(clf, 'churnModel.pkl')
我希望做的就是将由cross_val拟合的模型导出到joblib中。然而,当我在另一个项目中尝试加载它时,我得到了以下错误:
sklearn.exceptions.NotFittedError: Estimator not fitted, call `fit` before exploiting the model.
所以我猜测cross_val实际上并没有将拟合保存到我的clf中?我如何保存cross_val生成的模型拟合?
回答:
@人名 是对的。恐怕你得手动完成,但scikit-learn让这变得相当简单。cross_val_score创建了训练模型,但这些模型不会返回给你。下面的代码中,你将得到一个包含训练模型的列表(即clf_models)
from sklearn.model_selection import StratifiedKFoldfrom sklearn.ensemble import RandomForestClassifierfrom copy import deepcopykf = StratifiedKFold(n_splits=8)clf = RandomForestClassifier(class_weight="balanced")clf_models = []# 请记住,你的X和y在这里应该使用相同的索引kf.get_n_splits(X_data)for train_index, test_index in kf.split(X_data, y_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)
-通过@人名的建议编辑StratifiedKFold是一个更好的选择。这里我只是为了演示目的选择的。