C 在 LinearSVC sklearn (scikit-learn) 中的行为 [英] Behavior of C in LinearSVC sklearn (scikit-learn)

查看:62
本文介绍了C 在 LinearSVC sklearn (scikit-learn) 中的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先我创建一些玩具数据:

First I create some toy data:

n_samples=20
X=np.concatenate((np.random.normal(loc=2, scale=1.0, size=n_samples),np.random.normal(loc=20.0, scale=1.0, size=n_samples),[10])).reshape(-1,1)
y=np.concatenate((np.repeat(0,n_samples),np.repeat(1,n_samples+1)))
plt.scatter(X,y)

在图表下方可视化数据:

Below the graph to visualize the data:

然后我用 LinearSVC

from sklearn.svm import LinearSVC
svm_lin = LinearSVC(C=1)
svm_lin.fit(X,y)

我对 C 的理解是:

  • 如果C很大,那么错误分类是不能容忍的,因为惩罚会很大.
  • 如果 C 较小,则可以容忍错误分类以使边距(软边距)更大.
  • If C is very big, then misclassifications will not be tolerated, because the penalty will be big.
  • If C is small, misclassifications will be tolerated to make the margin (soft margin) larger.

使用C=1,我有下图(橙色线代表给定x值的预测),我们可以看到决策边界在7左右,所以C=1 足够大,不会让任何错误分类.

With C=1, I have the following graph (the orange line represent the predictions for given x values), and we can see the decision boundary is around 7, so C=1 is big enough to not let any misclassification.

X_test_svml=np.linspace(-1, 30, 300).reshape(-1,1)
plt.scatter(X,y)
plt.scatter(X_test_svml,svm_lin.predict(X_test_svml),marker="_")
plt.axhline(.5, color='.5')

C=0.001 为例,我希望决策边界在右侧,例如大约 11,但我得到了这个:

With C=0.001 for example, I am expecting the decision boundary to go to right-hand side, around 11 for example, but I got this:

我尝试使用另一个带有 SVC 功能的模块:

I tried with another module with the SVC function:

from sklearn.svm import SVC
svc_lin = SVC(kernel = 'linear', random_state = 0,C=0.01)
svc_lin.fit(X,y)

我成功得到了想要的输出:

I successfully got the desired output:

通过我的 R 代码,我得到了一些更容易理解的东西.(我使用了 e1071 包中的 svm 函数)

And with my R code, I got something more understandable. (I used svm function from e1071 package)

推荐答案

LinearSVCSVC(kernel=linear) 不是一回事.

区别在于:

  • SVC 和 LinearSVC 应该优化相同的问题,但实际上所有 liblinear 估计器都会惩罚截距,而 libsvm 则不会(IIRC).
  • 这会导致不同的数学优化问题,从而导致不同的结果.
  • 可能还有其他细微差别,例如缩放和默认损失函数(确保在 LinearSVC 中设置 loss='hinge').
  • 接下来,在多类分类中,liblinear 默认执行一对一,而 libsvm 执行一对一.

另见:https://stackoverflow.com/a/33844092/5025009

这篇关于C 在 LinearSVC sklearn (scikit-learn) 中的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆