在什么参数下,scikit-learn中的SVC和LinearSVC是等价的?

我阅读了这个讨论,内容是关于scikit-learn中SVC()LinearSVC()的区别。

现在我有一个二分类问题的数据集(对于这样的问题,两个函数之间的一对一/一对多策略差异可以忽略)。

我想尝试在什么参数下这两个函数会给我相同的结果。首先,当然,我们应该为SVC()设置kernel='linear'。然而,我就是无法从这两个函数中得到相同的结果。我在文档中找不到答案,有人能帮我找到我正在寻找的等价参数集吗?

更新:我修改了scikit-learn网站上的一个示例代码,显然它们是不一样的:

import numpy as npimport matplotlib.pyplot as pltfrom sklearn import svm, datasets# import some data to play withiris = datasets.load_iris()X = iris.data[:, :2]  # we only take the first two features. We could                      # avoid this ugly slicing by using a two-dim datasety = iris.targetfor i in range(len(y)):    if (y[i]==2):        y[i] = 1h = .02  # step size in the mesh# we create an instance of SVM and fit out data. We do not scale our# data since we want to plot the support vectorsC = 1.0  # SVM regularization parametersvc = svm.SVC(kernel='linear', C=C).fit(X, y)lin_svc = svm.LinearSVC(C=C, dual = True, loss = 'hinge').fit(X, y)# create a mesh to plot inx_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1xx, yy = np.meshgrid(np.arange(x_min, x_max, h),                     np.arange(y_min, y_max, h))# title for the plotstitles = ['SVC with linear kernel',          'LinearSVC (linear kernel)']for i, clf in enumerate((svc, lin_svc)):    # Plot the decision boundary. For that, we will assign a color to each    # point in the mesh [x_min, m_max]x[y_min, y_max].    plt.subplot(1, 2, i + 1)    plt.subplots_adjust(wspace=0.4, hspace=0.4)    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])    # Put the result into a color plot    Z = Z.reshape(xx.shape)    plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8)    # Plot also the training points    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired)    plt.xlabel('Sepal length')    plt.ylabel('Sepal width')    plt.xlim(xx.min(), xx.max())    plt.ylim(yy.min(), yy.max())    plt.xticks(())    plt.yticks(())    plt.title(titles[i])plt.show()

结果:前述代码的输出图


回答:

在数学意义上,你需要设置:

SVC(kernel='linear', **kwargs) # 默认使用RBF核

LinearSVC(loss='hinge', **kwargs) # 默认使用平方铰链损失

另一个难以轻易解决的问题是增加LinearSVC中的intercept_scaling,因为在这个实现中偏置是被正则化的(这在SVC中不是真的,在SVM中也不应该是真的 – 因此这不是SVM) – 因此它们将永远不会完全相等(除非你的问题中偏置为0),因为它们假设了两个不同的模型

  • SVC : 1/2||w||^2 + C SUM xi_i
  • LinearSVC: 1/2||[w b]||^2 + C SUM xi_i

个人认为,LinearSVC是scikit-learn开发者犯下的错误之一 – 这个类根本就不是线性SVM

在增加截距缩放(到10.0)后

SVMs

然而,如果你过度放大它 – 它也会失败,因为现在容差和迭代次数变得至关重要。

总结:LinearSVC不是线性SVM,如果没有必要,请不要使用它。

Related Posts

Keras Dense层输入未被展平

这是我的测试代码: from keras import…

无法将分类变量输入随机森林

我有10个分类变量和3个数值变量。我在分割后直接将它们…

如何在Keras中对每个输出应用Sigmoid函数?

这是我代码的一部分。 model = Sequenti…

如何选择类概率的最佳阈值?

我的神经网络输出是一个用于多标签分类的预测类概率表: …

在Keras中使用深度学习得到不同的结果

我按照一个教程使用Keras中的深度神经网络进行文本分…

‘MatMul’操作的输入’b’类型为float32,与参数’a’的类型float64不匹配

我写了一个简单的TensorFlow代码,但不断遇到T…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注