使用cross_val保存sklearn分类器的拟合

我有一个使用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是一个更好的选择。这里我只是为了演示目的选择的。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注