支持向量机(SVM)算法代码

来源:互联网 发布:linux教程pdf 编辑:程序博客网 时间:2024/06/04 18:30

1 sklearn实现svm的小例子

from sklearn import svmX = [[2,0],[1,1],[2,3]]y = [0,0,1]clf = svm.SVC(kernel = "linear")clf.fit(X,y)print(clf)print(clf.support_vectors_)print(clf.support_)print(clf.n_support_)#做预测
print("下面是测试案例:")print(clf.predict([[6,10]]))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

2 利用sklearn画出决定界限

import numpy as npimport pylab as plfrom sklearn import svmnp.random.seed(0)X = np.r_[np.random.randn(20,2) - [2,2],np.random.randn(20,2) + [2,2]]Y = [0] * 20 + [1] * 20clf = svm.SVC(kernel = "linear")clf.fit(X,Y)w = clf.coef_[0]a = -w[0]/w[1]xx = np.linspace(-5,5)yy = a * xx - (clf.intercept_[0]/w[1])b = clf.support_vectors_[0]yy_down = a * xx + (b[1]-a*b[0])b = clf.support_vectors_[-1]yy_up = a * xx + (b[1]-a*b[0])print("w: "+str(w))print("a: "+str(a))print("support_vectors_: "+str(clf.support_vectors_))print("coef_: "+str(clf.coef_))pl.plot(xx,yy,'k-')pl.plot(xx,yy_up,'k--')pl.plot(xx,yy_down,'k--')pl.scatter(clf.support_vectors_[:,0],clf.support_vectors_[:,1],s=80,facecolor='none')pl.scatter(X[:,0],X[:,1],c=Y,cmap=pl.cm.Paired)pl.axis('tight')pl.show()
原创粉丝点击