如何在GridSearchCV(随机森林分类器Scikit)上获得最佳估计器

58
我正在运行GridSearch CV来优化scikit中分类器的参数。完成后,我想知道哪些参数被选为最佳。但每次这样做时,我都会收到一个“AttributeError: 'RandomForestClassifier' object has no attribute 'best_estimator_'”错误,无法确定原因,因为它似乎是文档上合法的属性。
from sklearn.grid_search import GridSearchCV

X = data[usable_columns]
y = data[target]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

rfc = RandomForestClassifier(n_jobs=-1,max_features= 'sqrt' ,n_estimators=50, oob_score = True) 

param_grid = {
    'n_estimators': [200, 700],
    'max_features': ['auto', 'sqrt', 'log2']
}

CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= 5)

print '\n',CV_rfc.best_estimator_

产量:

`AttributeError: 'GridSearchCV' object has no attribute 'best_estimator_'

提供信息,max_features的“auto”和“sqrt”是相同的。它们都计算max_features = sqrt(n_features)。 - Marine
2个回答

95

在获得最佳参数组合之前,您需要对数据进行适配。

from sklearn.grid_search import GridSearchCV
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
# Build a classification task using 3 informative features
X, y = make_classification(n_samples=1000,
                           n_features=10,
                           n_informative=3,
                           n_redundant=0,
                           n_repeated=0,
                           n_classes=2,
                           random_state=0,
                           shuffle=False)


rfc = RandomForestClassifier(n_jobs=-1,max_features= 'sqrt' ,n_estimators=50, oob_score = True) 

param_grid = { 
    'n_estimators': [200, 700],
    'max_features': ['auto', 'sqrt', 'log2']
}

CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= 5)
CV_rfc.fit(X, y)
print CV_rfc.best_params_

16
不同的数据集将有不同的最优参数组合,即没有数据就没有最优参数组合。 - Ryan
1
考虑到您还将n_estimators传递给param_grid中的GridSearchCV,将其传递给RandomForestClassifier有什么意义? - sergzach
我没注意到,你说得对。我看到原始代码没有调用fit方法后,就只是简单地复制和粘贴了它。 - Ryan
1
在答案中,fit() 方法被调用到 Xy 上,所以问题中的 train_test_split 没有被使用。当使用 GridSearchCV 时,应该完全放弃这个分割吗? - Jack Fleeting
1
GridSearchCV 子库被错误地导入。 - Ṃųỻịgǻňạcểơửṩ
显示剩余3条评论

12

为了让事情更清晰,再补充一点。

该文档如下所述:

best_estimator_ : 估计器或字典:

在搜索中选择的估计器,即在留出数据上得分最高(如果指定了最小损失),给定评分函数的基础上得分最高的估计器。

当使用各种参数调用网格搜索时,它会根据给定的评分器函数选择得分最高的那个参数设置。 最佳估算器提供了导致最高得分的参数信息。

因此,这只能在拟合数据之后调用。


refit 会变成什么? - jtlz2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接