我想在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
)
答案 0 :(得分:0)
我不确定您是否可以为gridsearch或在gridsearch中进行条件自变量(感觉像是一个有用的功能)。但是,解决此问题的一种解决方案是,只需使用randomizesearchcv
参数为errors_raise
添加所有超参数,这将使您能够通过通常会失败并停止运行的迭代处理。像这样:
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,errors_raise=0)
在sklearn's SVC documentation中传递degree
不会有任何问题:
degree:int,可选(默认= 3) 多项式内核函数的阶数(“ poly”)。被所有其他内核忽略。
答案 1 :(得分:0)
不幸的是,GridsearchCV和RandomizedSearchCV不支持对超参数进行条件调整。
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])
}