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

sap*_*ico 37 python random-forest scikit-learn cross-validation

我正在运行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_
Run Code Online (Sandbox Code Playgroud)

产量:

`AttributeError: 'GridSearchCV' object has no attribute 'best_estimator_'
Run Code Online (Sandbox Code Playgroud)

Rya*_*yan 67

在获得最佳参数组合之前,必须先拟合数据.

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_
Run Code Online (Sandbox Code Playgroud)

  • 不同的数据集将具有不同的优化参数组合,即没有数据,没有最佳参数组合 (12认同)

小智 8

只是再添加一点以保持清楚。

该文件说如下:

best_estimator_ :估算器或字典:

通过搜索选择的估计量,即对遗漏数据给出最高分(或最小损失,如果指定)的估计量。

当使用各种参数调用网格搜索时,它会根据给定的评分器函数选择得分最高的那个。Best estimator 给出了导致最高分的参数的信息。

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