上一篇博客简单介绍了支持向量机SVM基本算法,这篇文章写一下它的简单应用
我们来用python求解一下超平面方程
from sklearn import svm
x=[[2,0],[1,1],[2,3]]#图中三个点
y=[0,0,1]#分类标记,(2,0)(1,1)为一类,标记为0,(2,3)标记为1
clf= svm.SVC(kernel='linear')#分类器,SVC即平时我们使用的SVM,kernel为核函数,这里用的是线性核函数
clf.fit(x,y)#x为特征矩阵,y为对应的class label
print(clf)
print(clf.support_vectors_) #分类器找到的support vector
print(clf.support_) #找到support index是哪几个
print(clf.n_support_) #support class label number
predictLabel = clf.predict([[-1,2]])#预测数据属于哪一类
print(predictLabel)
说明(1,1)和(2,3)是support vector,他们的标签时1和2,[1 1]说明在每一类中只找出了一个support vector,最后我们预测点(-1,2),发现它属于类别0
再来看一个稍微复杂的例子
#导入相关python包
import numpy as np
import pylab as pl
from sklearn import svm
创建一些线性可区分的点
# we create 40 separable points
np.random.seed(0)#固定数据集,使每次结果不变
X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]]#20行,两列,均值和方差都是2,前面数据在左下方,后面数据在右上方
Y = [0]*20 +[1]*20#前20个点归类为0,后20个点归类为1
建立模型
#fit the model
clf = svm.SVC(kernel='linear')#建立模型
clf.fit(X, Y)#建立模型
画出超平面
# get the separating hyperplane
#方程式:y = -(w_0/w_1) x + (w_3/w_1)
w = clf.coef_[0]#模型参数,二维
a = -w[0]/w[1]#画出直线的斜率
xx = np.linspace(-5, 5)#从-5到5之间产生一些连续x值
yy = a*xx - (clf.intercept_[0])/w[1]#截距,intercept_[0]取到的值为w_3
print ("w: ", w)
print ("a: ", a)
算出最大化边际的两条线
# plot the parallels to the separating hyperplane that pass through the support vectors
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 ("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()
nice,效果很ok