我想使用GridSearchCV贪婪地搜索支持向量分类器的整个参数空间。但是,LinearSVC和throw an exception禁止某些参数组合。特别是,dual
,penalty
和loss
参数有互斥的组合:
例如,这段代码:
from sklearn import svm, datasets
from sklearn.model_selection import GridSearchCV
iris = datasets.load_iris()
parameters = {'dual':[True, False], 'penalty' : ['l1', 'l2'], \
'loss': ['hinge', 'squared_hinge']}
svc = svm.LinearSVC()
clf = GridSearchCV(svc, parameters)
clf.fit(iris.data, iris.target)
返回ValueError: Unsupported set of arguments: The combination of penalty='l2' and loss='hinge' are not supported when dual=False, Parameters: penalty='l2', loss='hinge', dual=False
我的问题是:是否有可能使GridSearchCV跳过模型禁止的参数组合?如果没有,是否有一种简单的方法来构建一个不违反规则的参数空间?
我通过将error_score=0.0
传递给GridSearchCV
解决了这个问题:
error_score:'raise'(默认值)或数字
如果估算器拟合中发生错误,则分配给分数的值。如果设置为“raise”,则会引发错误。如果给出了数值,则引发FitFailedWarning。此参数不会影响重新启动步骤,这将始终引发错误。
如果您想完全避免探索特定的组合(无需等待遇到错误),您必须自己构建网格。 GridSearchCV可以获取一个dicts列表,其中探索列表中每个字典所跨越的网格。
在这种情况下,条件逻辑并不是那么糟糕,但对于更复杂的事情来说真的很乏味:
from sklearn import svm, datasets
from sklearn.model_selection import GridSearchCV
from itertools import product
iris = datasets.load_iris()
duals = [True, False]
penaltys = ['l1', 'l2']
losses = ['hinge', 'squared_hinge']
all_params = list(product(duals, penaltys, losses))
filtered_params = [{'dual': [dual], 'penalty' : [penalty], 'loss': [loss]}
for dual, penalty, loss in all_params
if not (penalty == 'l1' and loss == 'hinge')
and not ((penalty == 'l1' and loss == 'squared_hinge' and dual is True))
and not ((penalty == 'l2' and loss == 'hinge' and dual is False))]
svc = svm.LinearSVC()
clf = GridSearchCV(svc, filtered_params)
clf.fit(iris.data, iris.target)