GridSearchCV(sklearn)中的多个估计量

mik*_*ert 5 python scikit-learn grid-search

我正在查看有关的sklearn文档网页GridSearchCVGridSearchCV对象的属性之一是best_estimator_。所以这是我的问题。如何将多个估计量传递给GSCV对象?

使用字典,如: {'SVC()':{'C':10, 'gamma':0.01}, ' DecTreeClass()':{....}}

Viv*_*mar 6

GridSearchCV处理参数。它将训练多个估计器(但同一类(SVC或DecisionTreeClassifier或其他分类器之一),其参数组合与中指定的不同param_gridbest_estimator_是对数据效果最好的估计器。

因此,本质上best_estimator_是使用最佳找到的参数初始化的同一类对象。

因此,在基本设置中,您不能在网格搜索中使用多个估算器。

但是,作为一种解决方法,当使用管道中可以使用多个估算器时"parameter",GridSearchCV可以在该管道中设置估算器。

像这样:

from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import load_iris
iris_data = load_iris()
X, y = iris_data.data, iris_data.target


# Just initialize the pipeline with any estimator you like    
pipe = Pipeline(steps=[('estimator', SVC())])

# Add a dict of estimator and estimator related parameters in this list
params_grid = [{
                'estimator':[SVC()],
                'estimator__C': [1, 10, 100, 1000],
                'estimator__gamma': [0.001, 0.0001],
                },
                {
                'estimator': [DecisionTreeClassifier()],
                'estimator__max_depth': [1,2,3,4,5],
                'estimator__max_features': [None, "auto", "sqrt", "log2"],
                },
               # {'estimator':[Any_other_estimator_you_want],
               #  'estimator__valid_param_of_your_estimator':[valid_values]

              ]

grid = GridSearchCV(pipe, params_grid)
Run Code Online (Sandbox Code Playgroud)

您可以在列表中添加任意数量的字典params_grid,但要确保每个字典都具有与兼容的参数'estimator'