[英]Scikit-learn using GridSearchCV on DecisionTreeClassifier
我嘗試在 DecisionTreeClassifier 上使用 GridSearchCV,但得到以下錯誤:TypeError: unbound method get_params() must be called with DecisionTreeClassifier instance as first argument ( got nothing instead)
這是我的代碼:
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)
在調用GridSearchCV
方法時,第一個參數應該是DecisionTreeClassifier
的實例化對象,而不是類的名稱。 應該是
clf = GridSearchCV(DecisionTreeClassifier(), tree_para, cv=5)
查看此處的示例以獲取更多詳細信息。
希望有幫助!
關於參數的另一方面是網格搜索可以使用不同的參數組合運行。 下面提到的參數將檢查criterion
與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}]
在這種情況下,網格搜索將在兩組參數上運行,首先是criterion
和max_depth
每個組合,其次,僅針對所有提供的min_samples_leaf
值
需要在分類器前加一個():
clf = GridSearchCV(DecisionTreeClassifier(), tree_para, cv=5)
這是決策樹網格搜索的代碼
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_
如果問題仍然存在,請嘗試更換:
from sklearn.grid_search import GridSearchCV
與
from sklearn.model_selection import GridSearchCV
這聽起來很愚蠢,但我遇到了類似的問題,我設法使用這個技巧解決了這些問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.