5.2支持向量机(SVM)算法(上)应用

线性可区分情况下的代码实现:

例子:

      

'''
通过调用sklearn svm工具包来实现1
'''
from sklearn import svm

x = [[2,0],[1,1],[2,3]]     #三个点 (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_)

40个点的情况:

#coding:gbk
#coding:utf-8
'''
Created on 2018年7月12日

@author: YaHuYang
'''
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()

结果:

                               

猜你喜欢

转载自blog.csdn.net/weixin_41790863/article/details/81022023
今日推荐