gpt4 book ai didi

python - 使用 GridSearchCV 时跳过禁止的参数组合

转载 作者:太空狗 更新时间:2023-10-29 20:37:42 25 4
gpt4 key购买 nike

我想使用 GridSearchCV 贪婪地搜索支持向量分类器的整个参数空间.但是,LinearSVC 禁止某些参数组合和 throw an exception .特别是,dualpenaltyloss 参数存在互斥组合:

例如,这段代码:

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:不支持的参数集:当 dual=False 时不支持 penalty='l2' 和 loss='hinge' 的组合,参数:penalty='l2',loss='hinge',双=假

我的问题是:是否可以让 GridSearchCV 跳过模型禁止的参数组合?如果不是,有没有简单的方法构造一个不违反规则的参数空间?

最佳答案

我通过将 error_score=0.0 传递给 GridSearchCV 解决了这个问题:

error_score : ‘raise’ (default) or numeric

Value to assign to thescore if an error occurs in estimator fitting. If set to ‘raise’, theerror is raised. If a numeric value is given, FitFailedWarning israised. This parameter does not affect the refit step, which willalways raise the error.

更新:较新版本的 sklearn 打印出一堆 ConvergenceWarningFitFailedWarning。我很难用 contextlib.suppress 压制它们,但是 there is a hack around that涉及测试上下文管理器:

from sklearn import svm, datasets 
from sklearn.utils._testing import ignore_warnings
from sklearn.exceptions import FitFailedWarning, ConvergenceWarning
from sklearn.model_selection import GridSearchCV

with ignore_warnings(category=[ConvergenceWarning, FitFailedWarning]):
iris = datasets.load_iris()
parameters = {'dual':[True, False], 'penalty' : ['l1', 'l2'], \
'loss': ['hinge', 'squared_hinge']}
svc = svm.LinearSVC()
clf = GridSearchCV(svc, parameters, error_score=0.0)
clf.fit(iris.data, iris.target)

关于python - 使用 GridSearchCV 时跳过禁止的参数组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43009566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com