RandomForestClassifier对象没有属性'estimators'

时间:2018-01-28 22:56:58

标签: python random-forest

我试图在少数分类模型上运行GridsearchCV以优化它们。我的代码如下:

models = ['Random Forest','KNN','Decision Tree'] 
classifiers ={RandomForestClassifier(random_state=3):{"max_depth": 
[2,3,4,5,6,7,8,9,10,11,12]
        ,"min_samples_split" :[2,3,4,5,6]
        ,"n_estimators" : [10]
        ,"min_samples_leaf": [1,2,3,4,5]
        ,"max_features": (4,5,6,"sqrt")
        ,"criterion": ('gini','entropy')},
KNeighborsClassifier():{'n_neighbors':range(15,30), 
          'p':[1,2],
          'weights':['uniform','distance']}
}

class_names = list(y_lab.values)
for model, classifier in zip(models,classifiers.keys()):
        clf = GridSearchCV(estimator = classifier,param_grid = 
classifier[classifier],cv=5, scoring="roc_auc", n_jobs= -1)
        clf.fit(X_train, y_train)
        print ('For model %s' %model+ ', the cross valudation score is %.5f'% 
clf.best_score_)  
        y_pred = clf.best_estimator_.predict(X_test)
        print ('The accuracy score for the model %s' % model + 'is %.5f' + 
accuracy_score(y_pred,y_test))
        cm = confusionMatrix(y_pred,y_test)

然而,结果产生: AttributeError:'RandomForestClassifier'对象没有属性'estimators_' 此代码模式以前有效,但不知道导致此错误消息的原因

1 个答案:

答案 0 :(得分:0)

我可以使用以下代码重现您的问题:

for model, classifier in zip(models,classifiers.keys()):
    print(classifier[classifier])

AttributeError: 'RandomForestClassifier' object has no attribute 'estimators_'

相反,下面的代码不会导致任何错误。所以,你需要重新思考你的循环。

for model, classifier, classifier_param in zip(models,classifiers.keys(), classifiers.values()):
    print(model, classifier, classifier_param)

Random Forest RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
            max_depth=None, max_features='auto', max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1,
            oob_score=False, random_state=None, verbose=0,
            warm_start=False) {'max_depth': [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 'min_samples_split': [2, 3, 4, 5, 6], 'n_estimators': [10], 'min_samples_leaf': [1, 2, 3, 4, 5], 'max_features': (4, 5, 6, 'sqrt'), 'criterion': ('gini', 'entropy')}
KNN KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
           metric_params=None, n_jobs=1, n_neighbors=5, p=2,
           weights='uniform') {'n_neighbors': range(15, 30), 'p': [1, 2], 'weights': ['uniform', 'distance']}