使用sklearn里面的svm进行数据分类
画出分类平面,支持向量
对未知标签的数据进行分类预测
#coding=utf-8
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
# 自己产生的数据 两类样本
np.random.seed(0)
N = 20
x0 = np.random.uniform(0,5,N)
y0 = np.random.uniform(3,9,N)
data0 = list(zip(x0,y0)) # 2 lists ---> 1 list
x1 = np.random.uniform(4,8,N)
y1 = np.random.uniform(-1,4,N)
data1 = list(zip(x1,y1))
# 原来是list 需要转成array才可以用svm
data0 = np.array(data0)
data1 = np.array(data1)
X = np.concatenate((data0,data1),axis=0) # array拼接起来
Y = [0] * N + [1]* N # 自己打上标签
# sklearn自带的SVM直接算出来了分类平面的参数
clf = svm.SVC(kernel = 'linear')
clf.fit(X,Y)
# 分类平面
w = clf.coef_[0]
a = -w[0]/w[1]
xx = np.linspace(-2,10)
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])
# 预测未知标签的点是哪一类
xx_predict = np.array([[0.5,3],
[2.4,4],
[2,10],
[3,5]])
yy_predict = clf.predict(xx_predict)
print "The class of the data are:", yy_predict
plt.title('data')
plt.xlabel('x')
plt.ylabel('y')
plt.scatter(x0,y0,c='blue',marker='o')
plt.scatter(x1,y1,c='black',marker='x')
plt.plot(xx,yy,'r-')
plt.plot(xx,yy_down,'b--')
plt.plot(xx,yy_up,'k--')
plt.scatter(xx_predict[:,0],xx_predict[:,1],c='red',marker='s')
plt.show()
结果如下图