我想在sklearn中使用RandomizedSearchCV在我的数据集中搜索支持向量分类器的最佳超参数值。我正在优化的超参数是“内核”,“ C”和“ gamma”。但是,在使用“多边形”内核的情况下,我还要优化第四个超参数“度”(多项式内核函数的索引)。

我意识到,当内核不是“ poly”时,度超参数将被忽略,因此我可以将度包括在我提供给RandomizedSearchCV的params字典中(就像我在下面的代码中所做的那样)。但是,理想情况下,我想在非多边形核以及每个度数的多边形之间进行统一搜索,即我想在例如[(kernel =“ linear”),(kernel =“ rbf”),(kernel =“ poly”,度= 2),(kernel =“ poly”,度= 3)]。因此,我想知道是否有可能有条件地引入用于调整的超参数,即,如果kernel =“ poly” degree = np.linspace(2,5,4),否则degree = 0。

我在RandomizedSearchCV文档中找不到这样的示例,因此想知道这里是否有人遇到过同样的问题并且能够提供帮助。谢谢!

from sklearn.svm import SVC
from sklearn.model_selection import RandomizedSearchCV
from sklearn.model_selection import StratifiedKFold

clf = SVC()
params = {'kernel': ['linear', 'poly', 'rbf', 'sigmoid'],
          'degree': np.linspace(2, 5, 4),
          'C': np.logspace(-3, 5, 17),
          'gamma': np.logspace(-3, 5, 17)}

random_search = RandomizedSearchCV(
    estimator=clf, param_distributions=params, n_iter=200, n_jobs=-1,
    cv=StratifiedKFold(n_splits=5), iid=False
)

最佳答案

不幸的是,GridsearchCVRandomizedSearchCV不支持超参数的条件调整。

Hyperopt支持条件调整超参数,请检查此wiki以获取更多详细信息。

例:

space4svm = {
    'C': hp.uniform('C', 0, 20),
    'kernel': hp.choice('kernel', [
            {'ktype': 'linear'},
            {'ktype': 'poly', 'degree': hp.lognormal('degree', 0, 1)},
            ]),
    'gamma': hp.uniform('gamma', 0, 20),
    'scale': hp.choice('scale', [0, 1]),
    'normalize': hp.choice('normalize', [0, 1])
}

关于python - 在scikit-learn中使用RandomizedSearchCV对超参数进行条件调整,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58168297/

10-10 02:33