首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RandomForestClassifier对象没有“estimators”属性

RandomForestClassifier对象没有“estimators”属性
EN

Stack Overflow用户
提问于 2018-01-29 06:56:58
回答 1查看 11.6K关注 0票数 1

我正在尝试在一些分类模型上运行GridsearchCV,以便对它们进行优化。我的代码如下:

代码语言:javascript
复制
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_’属性此代码模式以前工作过,但不知道是什么导致了这条错误消息

EN

回答 1

Stack Overflow用户

发布于 2018-01-29 10:52:03

我可以用下面的代码重现你的问题:

代码语言:javascript
复制
for model, classifier in zip(models,classifiers.keys()):
    print(classifier[classifier])

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

相反,下面的代码不会导致任何错误。因此,您需要重新考虑您的循环。

代码语言:javascript
复制
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']}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48492261

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档