LinearSVC() 與 SVC(kernel='linear') 的區(qū)別概括如下:
- LinearSVC() 最小化 hinge loss的平方,
SVC(kernel='linear') 最小化 hinge loss; - LinearSVC() 使用 one-vs-rest 處理多類問題,
SVC(kernel='linear') 使用 one-vs-one 處理多類問題; - LinearSVC() 使用linear執(zhí)行,
SVC(kernel='linear')使用libsvm執(zhí)行; - LinearSVC() 可以選擇正則項和損失函數(shù),
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 實現(xiàn)使用隨機數(shù)選擇特征,因此,對于相同的輸入可能會得到不同的結果。liblinear使用稀疏的數(shù)據(jù)表示,會產(chǎn)生內(nèi)存拷貝。
線性模型有線性決策邊界(交叉的超平面),而非線性核模型(多項式或者高斯RBF)的彈性非線性決策邊界的形狀由核種類和參數(shù)決定。
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()