14

我尝试在 DecisionTreeClassifier 上使用 GridSearchCV,但出现以下错误:TypeError: unbound method get_params() must be called with DecisionTreeClassifier instance as first argument (什么都没有代替)

这是我的代码:

from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.model_selection import GridSearchCV
from sklearn.cross_validation import  cross_val_score

X, Y = createDataSet(filename)
tree_para = {'criterion':['gini','entropy'],'max_depth':[4,5,6,7,8,9,10,11,12,15,20,30,40,50,70,90,120,150]}
clf = GridSearchCV(DecisionTreeClassifier, tree_para, cv=5)
clf.fit(X, Y)
4

5 回答 5

12

在您对GridSearchCV方法的调用中,第一个参数应该是实例化的对象,DecisionTreeClassifier而不是类的名称。它应该是

clf = GridSearchCV(DecisionTreeClassifier(), tree_para, cv=5)

在此处查看示例以获取更多详细信息。

希望有帮助!

于 2016-08-02T00:02:39.900 回答
4

关于参数的另一个方面是可以使用不同的参数组合运行网格搜索。下面提到的参数将检查criterionwith的不同组合max_depth

tree_param = {'criterion':['gini','entropy'],'max_depth':[4,5,6,7,8,9,10,11,12,15,20,30,40,50,70,90,120,150]}

如果需要,网格搜索可以在多组参数候选上运行:

例如:

tree_param = [{'criterion': ['entropy', 'gini'], 'max_depth': max_depth_range},
              {'min_samples_leaf': min_samples_leaf_range}]

在这种情况下,网格搜索将在两组参数上运行,首先是criterionmax_depth和的每个组合,第二个,仅针对所有提供的值min_samples_leaf

于 2019-09-04T02:13:28.853 回答
1

您需要在分类器前面添加一个():

clf = GridSearchCV(DecisionTreeClassifier(), tree_para, cv=5)
于 2017-12-21T05:52:44.167 回答
1

这是决策树网格搜索的代码

from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV

def dtree_grid_search(X,y,nfolds):
    #create a dictionary of all values we want to test
    param_grid = { 'criterion':['gini','entropy'],'max_depth': np.arange(3, 15)}
    # decision tree model
    dtree_model=DecisionTreeClassifier()
    #use gridsearch to test all values
    dtree_gscv = GridSearchCV(dtree_model, param_grid, cv=nfolds)
    #fit model to data
    dtree_gscv.fit(X, y)
    return dtree_gscv.best_params_
于 2019-08-22T13:19:50.607 回答
0

如果问题仍然存在,请尝试更换:

from sklearn.grid_search import GridSearchCV

from sklearn.model_selection import GridSearchCV

这听起来很愚蠢,但我遇到了类似的问题,我设法使用这个技巧解决了这些问题。

于 2017-06-01T14:56:42.400 回答