首先要安装svm的安装包的
这是一个在网上看到的例子,自己敲了下,当作练习了~
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66from sklearn import svm import numpy as np import matplotlib.pyplot as plt # 设置子图数量和尺寸 fig, axes = plt.subplots(nrows=2, ncols=2,figsize=(7,7)) ax0, ax1, ax2, ax3 = axes.flatten() ''' 说明1: 核函数(这里简单介绍了sklearn中svm的四个核函数,还有precomputed及自定义的) LinearSVC:主要用于线性可分的情形。参数少,速度快,对于一般数据,分类效果已经很理想 RBF:主要用于线性不可分的情形。参数多,分类结果非常依赖于参数 polynomial:多项式函数,degree 表示多项式的程度-----支持非线性分类 Sigmoid:在生物学中常见的S型的函数,也称为S型生长曲线 说明2:根据设置的参数不同,得出的分类结果及显示结果也会不同 ''' # 设置四个子图的标题 titles = ['LinearSVC (linear kernel)', 'SVC with polynomial (degree 3) kernel', 'SVC with RBF kernel', ##这个是默认的 'SVC with Sigmoid kernel'] # 准备训练样本 x=[[11,8],[32,20],[13,15],[13,35],[25,35],[24,40],[17,80],[26,49]] y=[1,1,-1,-1,1,-1,-1,1] # 生成随机试验数据(15行2列) rdm_arr = np.random.randint(1, 15, size=(15,2)) def drawPoint(ax,clf,tn): # 绘制样本点,设置颜色、样式 for i in x: ax.set_title(titles[tn]) res = clf.predict(np.array(i).reshape(1, -1)) if res > 0: ax.scatter(i[0],i[1],c='r',marker='*') else : ax.scatter(i[0],i[1],c='g',marker='*') # 绘制实验点,设置颜色、样式 for i in rdm_arr: res = clf.predict(np.array(i).reshape(1, -1)) if res > 0: ax.scatter(i[0],i[1],c='r',marker='.') else : ax.scatter(i[0],i[1],c='g',marker='.') if __name__=="__main__": # 依次选择四个核函数来进行运算 for n in range(0,4): if n==0: clf = svm.SVC(kernel='linear').fit(x, y) drawPoint(ax0,clf,0) elif n==1: clf = svm.SVC(kernel='poly', degree=3).fit(x, y) drawPoint(ax1,clf,1) elif n==2: clf= svm.SVC(kernel='rbf').fit(x, y) drawPoint(ax2,clf,2) else : clf= svm.SVC(kernel='sigmoid').fit(x, y) drawPoint(ax3,clf,3) plt.show()
最后
以上就是孝顺黑猫最近收集整理的关于机器学习 | SVM的一个练习小例子的全部内容,更多相关机器学习内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复