機器學習---支持向量機(SVM)算法應用(上)

1.SVM線性可分sklearn簡單實例

結合上一節實例看
code:

# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Justin Chan

from sklearn import svm

#三個分類點
x = [[2,0],[1,1],[2,3]]
#將三個點分成兩類,前兩個點類別爲0,後一個點類別爲1
y = [0,0,1]
clf = svm.SVC(kernel='linear')
clf.fit(x,y)

print(clf)

#get support vectors獲取支持向量點列表
print(clf.support_vectors_)

#get indices of support vectors獲取支持向量點在向量列表中的索引值
print(clf.support_)

#get number of support vectors for each class獲取每一類中支持向量點的個數
print(clf.n_support_)

#預測分類點[3,0]
print(clf.predict([[3,0]]))

result:

SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape='ovr', degree=3, gamma='auto', kernel='linear',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False)
[[ 1.  1.]
 [ 2.  3.]]#支持向量點座標分別爲[1,1][2,3]
[1 2]#支持向量點的索引是1和2,另一個索引0的點[2,0]不是支持向量點
[1 1]#兩類都各有一個支持向量點
[0]#預測分類點類別爲0

2.SVM線性可分sklearn複雜實例

# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Justin Chan

import numpy as np
#python中可以把函數畫圖的模塊sudo pip install matplotlib
import pylab as pl

from sklearn import svm

#we creat 40 separable points
#seed隨機生成點,這裏給定一個參數0,固定住隨機生成的結果,保證每次運行出來的隨機值是一致的。
np.random.seed(0)
#隨機產生20個點,-[2,2]均值爲2,方差爲2,正態分佈在左側,+[2,2]均值爲2,方差爲2,正態分佈在右側
X = np.r_[np.random.randn(20,2)-[2,2],np.random.randn(20,2)+[2,2]]
#歸類標記
Y = [0]*20 + [1]*20

#fit the model
clf = svm.SVC(kernel='linear')
clf.fit(X,Y)

#下面就是通過生成的點畫圖

#get the separating hyperplane
w = clf.coef_[0]
#直線斜率
a = -w[0]/w[1]
#產生從-5到5一些連續的值
xx = np.linspace(-5,5)
#畫出點斜式方程
yy = a*xx - (clf.intercept_[0])/w[1]

#plot the parallels to the separating hyperplane that pass through the support vectors
#三條直線是平行的,斜率一樣,截距不同yy是中間的線,yy_down和yy_up分別是支持向量的線
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("xx:",xx)
#print("yy:",yy)
print("support vectors:",clf.support_vectors_)
print("clf.coef_:",clf.coef_)

#plot the line,the points,and the nearest vectors to the plane
pl.plot(xx,yy,'k-')
pl.plot(xx,yy_down,'k--')
pl.plot(xx,yy_up,'k--')

#使用scatter把support vectors的點單獨圈出來
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()

result:

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]]

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章