1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2017/8/1 21:58
 4 # @Author  : banshaohuan
 5 # @File    : SKLearnExample.py
 6 # @Software: PyCharm
 7 
 8 from sklearn import svm
 9 
10 x = [[2, 0], [1, 1], [2, 3]]
11 y = [0, 0, 1]   # 将上面的三个点进行分类,用0、1代表
12 clf = svm.SVC(kernel="linear")  # 方程SVC
13 clf.fit(x, y)   # 建立分类器模型,参数一:list,每一行代表一个实例;参数二:每一个实例所对应的label
14 
15 print(clf)
16 
17 print(clf.support_vectors_)     # support_vectors_:支持向量是哪几个
18 
19 print(clf.support_)     # support_:支持向量点的下标
20 
21 print(clf.n_support_)   # n_support_:分好的每个类中有几个支持向量
22 
23 print(clf.predict([2, 0]))  # 对存在的点进行分类

 

难一点的

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2017/8/1 22:14
 4 # @Author  : banshaohuan
 5 # @File    : SKLearnExampleHard.py
 6 # @Software: PyCharm
 7 
 8 print(__doc__)
 9 
10 import numpy as np
11 import pylab as pl
12 from sklearn import svm
13 
14 np.random.seed(0)   # 固定一下每次运行时随机产生的数不变
15 X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]]    # 随机产生一些点,让他们能够通过一条线分开
16 Y = [0] * 20 + [1] * 20
17 
18 # 建立模型
19 clf = svm.SVC(kernel='linear')
20 clf.fit(X, Y)
21 
22 w = clf.coef_[0]
23 a = -w[0] / w[1]    # 计算斜率
24 xx = np.linspace(-5, 5)    # 产生一些连续的x的值
25 yy = a * xx - (clf.intercept_[0]) / w[1]
26 
27 b = clf.support_vectors_[0]
28 yy_down = a * xx + (b[1] - a * b[0])
29 b = clf.support_vectors_[-1]
30 yy_up = a * xx + (b[1] - a * b[0])
31 
32 print('w: ', w)
33 print('a:',a)
34 
35 print('support_vectors_: ', clf.support_vectors_)
36 print('coef_: ', clf.coef_)
37 
38 
39 pl.plot(xx, yy, 'k-')
40 pl.plot(xx, yy_down, 'k--')
41 pl.plot(xx, yy_up, 'k--')
42 
43 pl.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, facecolors='none')
44 
45 pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired)
46 
47 pl.axis('tight')
48 pl.show()