python SVM

使用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()

结果如下图
SVM Result

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值