![](/img/trans.png)
[英]Scikit-learn: use cross-validation on whole dataset after hyperparameters tuning
[英]Conditional tuning of hyperparameters with RandomizedSearchCV in scikit-learn
我想在 sklearn 中使用 RandomizedSearchCV 在我的数据集上搜索支持向量分类器的最佳超参数值。 我正在优化的超参数是“kernel”、“C”和“gamma”。 但是,在“poly”kernel 的情况下,我还想优化第四个超参数“degree”(多项式 kernel 函数的索引)。
我意识到,由于当 kernel 不是“poly”时,度超参数被忽略,所以我可以在提供给 RandomizedSearchCV 的参数字典中包含度数(正如我在下面的代码中所做的那样)。 但是,理想情况下,我想在非多边形内核加上每个多边形 kernel 的度数上进行均匀搜索,即我想在例如 [(kernel="linear")、(kernel="rbf")、(kernel= "poly", degree=2), (kernel="poly", degree=3)]。 因此,我想知道是否可以有条件地引入一个超参数进行调整,即如果 kernel="poly" degree=np.linspace(2, 5, 4), else 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
)
我不确定您是否可以为 gridsearch 或在 gridsearch 内创建有条件的 arguments(这感觉像是一个有用的功能)。 但是,围绕此问题解决 go 的一种方法是简单地设置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 的 SVC 文档中,您通过degree
应该没有任何问题:
degree: int, optional (default=3) 多项式 kernel function ('poly') 的度数。 被所有其他内核忽略。
不幸的是, 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])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.