2016-12-21 34 views
0

我有一个分类器我适合使用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 joblib 
joblib.dump(clf, 'churnModel.pkl') 

基本上就是我想要做的是采取是越来越契合通过cross_val,并出口到JOBLIB模型。然而,当我试图把它在一个单独的项目,我得到:

sklearn.exceptions.NotFittedError: Estimator not fitted, call `fit` before exploiting the model. 

所以我猜cross_val实际上并没有拯救适合我的CLF?我如何坚持cross_val生成的模型?

+1

哪个型号?当你交叉验证时,你适合*几个*模型。 –

回答

0

juanpa.arrivillaga是对的。恐怕你必须手动完成,但scikit-learn使它非常容易。 cross_val_score正在制作不会返回给您的深层复印件。下面你会在列表中有deepcopied模型(即clf_models)通过juanpa.arrivillaga的建议

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) 

-edit StratifiedKFold是一个更好的选择。只是为了示范。

+0

可能更好地使用'StratifiedKFold' –

+0

所以,如果我理解正确,clf_models是8个模型的列表拟合到父数据的子集的权利?有没有最好的做法,让这个单一的模型?我只挑选得分最高的那个,还是有办法将它们混合? –

+0

这是正确的,clf_models是8个拟合模型的列表。如果您使用交叉验证,目的通常是为模型找到好的超参数。如果这意味着模型未训练的数据中的折叠对于未来的数据集特别不具有代表性,那么选择具有最佳分数的模型可能是正确的选择。你应该看看这是否属实。这些事通常根据具体情况决定; RandomForestClassifier可能甚至不会为您的情况产生任何结果。总之,这取决于。 – itzjustricky