美文网首页学习scikit-learn
LinearSVC() 与 SVC(kernel='l

LinearSVC() 与 SVC(kernel='l

作者: DayDayUp_hhxx | 来源:发表于2017-06-19 18:51 被阅读812次

LinearSVC() 与 SVC(kernel='linear') 的区别概括如下:

  • LinearSVC() 最小化 hinge loss的平方,
    SVC(kernel='linear') 最小化 hinge loss;
  • LinearSVC() 使用 one-vs-rest 处理多类问题,
    SVC(kernel='linear') 使用 one-vs-one 处理多类问题;
  • LinearSVC() 使用linear执行,
    SVC(kernel='linear')使用libsvm执行;
  • LinearSVC() 可以选择正则项和损失函数,
    SVC(kernel='linear')使用默认设置。

LinearSVC

sklearn.svm.LinearSVC(penalty='l2', loss='squared_hinge', dual=True, tol=0.0001, C=1.0, multi_class='ovr', fit_intercept=True, intercept_scaling=1, class_weight=None, verbose=0, random_state=None, max_iter=1000)

  • loss:string, ‘hinge’ or ‘squared_hinge’ (default=’squared_hinge’)
  • penalty : string, ‘l1’ or ‘l2’ (default=’l2’)

注意:底层 C 实现使用随机数选择特征,因此,对于相同的输入可能会得到不同的结果。liblinear使用稀疏的数据表示,会产生内存拷贝。


线性模型有线性决策边界(交叉的超平面),而非线性核模型(多项式或者高斯RBF)的弹性非线性决策边界的形状由核种类和参数决定。

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm,datasets

iris=datasets.load_iris()
x=iris.data[:,:2] #2D graph,2features
y=iris.target

h=0.02
C=1.0

svc=svm.SVC(kernel='linear',C=C).fit(x,y)
rbf_svc=svm.SVC(kernel='rbf',gamma=0.7,C=C).fit(x,y)
poly_svc=svm.SVC(kernel='poly',degree=3,C=C).fit(x,y)
lin_svc=svm.LinearSVC(C=C).fit(x,y)

x_min,x_max=x[:,0].min()-1,x[:,0].max()+1
y_min,y_max=x[:, 1].min()-1,x[:,1].max()+1
xx,yy=np.meshgrid(np.arange(x_min,x_max,h),np.arange(y_min,y_max,h))

titles=['SVC with linear kernel',
          'LinearSVC (linear kernel)',
          'SVC with RBF kernel',
          'SVC with polynomial (degree 3) kernel']

for i,clf in enumerate((svc,lin_svc,rbf_svc,poly_svc)):
    plt.subplot(2,2,i+1)
    plt.subplots_adjust(wspace=0.4,hspace=0.4)
    
    z=clf.predict(np.c_[xx.ravel(),yy.ravel()])
    z=z.reshape(xx.shape)
    plt.contourf(xx,yy,z,cmap=plt.cm.coolwarm,alpha=0.8)
    
    plt.scatter(x[:,0],x[:,1],c=y,cmap=plt.cm.coolwarm)
    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()

来源:http://scikit-learn.org/stable/auto_examples/svm/plot_iris.html#sphx-glr-auto-examples-svm-plot-iris-py

相关文章

网友评论

    本文标题: LinearSVC() 与 SVC(kernel='l

    本文链接:https://www.haomeiwen.com/subject/lxhnqxtx.html