機器學習算法-SVM

1、SVM原理
http://blog.csdn.net/alvine008/article/details/9097105

2、python實現

#coding:gbk
#coding:utf-8
'''
Created on 2016年6月5日

@author: Administrator
'''
import numpy as np
import pylab as pl
from sklearn import svm

#創建40個線性可分的點
np.random.seed(0)#0是爲了每次運行時隨機產生的點不變
X = np.r_[np.random.randn(20,2) - [2,2],np.random.randn(20,2) + [2,2]]
Y = [0]*20 + [1]*20#將前20個點歸類爲0類,後20個點歸類爲1類

#建立模型
clf = svm.SVC(kernel = 'linear')
clf.fit(X,Y)

#得到可分的超平面
w = clf.coef_[0]#得到w是二維的,w0,w1
a = -w[0]/w[1]#直線的斜率
xx = np.linspace(-5,5)#在(-5,5)之間產生連續的x的值
yy = a*xx - (clf.intercept_[0]/w[1])#計算出y的值

#通過支持向量畫兩邊的平行線
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:',w)
print('a:',a)
print('support_vectors_:',clf.support_vectors_)
print('clf.coef_:',clf.coef_)

#畫出線,點和最近的向量
pl.plot(xx,yy,'k-')#畫出分割線
pl.plot(xx,yy_down,'k--')
pl.plot(xx,yy_up,'k--')

pl.scatter(clf.support_vectors_[:,0],clf.support_vectors_[:,1],
           s = 80,facecolors = 'none')#顯示支持向量
pl.scatter(X[:,0],X[:,1],c=Y,cmap=pl.cm.Paired)#圈出支持向量

pl.axis('tight')
pl.show()

結果:
w: [ 0.90230696 0.64821811]
a: -1.39198047626
support_vectors_: [[-1.02126202 0.2408932 ]
[-0.46722079 -0.53064123]
[ 0.95144703 0.57998206]]
clf.coef_: [[ 0.90230696 0.64821811]]

這裏寫圖片描述

發佈了101 篇原創文章 · 獲贊 57 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章