python导入鸢尾花数据集_Python实现鸢尾花数据集分类问题——基于skearn的SVM

更新时间:2023-07-04 04:18:35 阅读: 评论:0

python导⼊鸢尾花数据集_Python实现鸢尾花数据集分类问题
——基于skearn的SVM
1 #!/usr/bin/env python
2 #encoding: utf-8
3 __author__ = 'Xiaolin Shen'
4 from sklearn importsvm
5 importnumpy as np
6 from sklearn importmodel_lection
7 importmatplotlib.pyplot as plt
8 importmatplotlib as mpl
9 from matplotlib importcolors10
11
12
13 #当使⽤numpy中的loadtxt函数导⼊该数据集时,假设数据类型dtype为浮点型,但是很明显数据集的第五列的数据类型是字符串并不是浮点型。
14 #因此需要额外做⼀个⼯作,即通过loadtxt()函数中的converters参数将第五列通过转换函数映射成浮点类型的数据。
15 #⾸先,我们要写出⼀个转换函数:
16 #定义⼀个函数,将不同类别标签与数字相对应
17 defiris_type(s):18 class_label={b'Iris-tosa':0,b'Iris-versicolor':1,b'Iris-virginica':2}19 returnclass_label[s]20
21 #(1)使⽤numpy中的loadtxt读⼊数据⽂件
上海广告设计培训22 filepath='' #数据⽂件路径
23 data=np.loadtxt(filepath,dtype=float,delimiter=',',converters={4:iris_type})24 #以上4个参数中分别表⽰:
25 #filepath :⽂件路径。eg:C:/。
26 #dtype=float :数据类型。eg:float、str等。
27 #delimiter=',' :数据以什么分割符号分割。eg:‘,’。
28 #converters={4:iris_type} :对某⼀列数据(第四列)进⾏某种类型的转换,将数据列与转换函数进⾏映射的字典。eg:{1:fun},含义是将第2列对应转换函数进⾏转换。
摘取梦想的启明星29 #converters={4: iris_type}中“4”指的是第5列。
30
31 #print(data)
32 #读⼊结果⽰例为:
33 #[[ 5.1 3.5 1.4 0.2 0. ]
重庆在职研究生34 #[ 4.9 3. 1.4 0.2 0. ]搭档英语怎么说
35 #[ 4.7 3.2 1.3 0.2 0. ]
36 #[ 4.6 3.1 1.5 0.2 0. ]
37 #[ 5. 3.6 1.4 0.2 0. ]]
38
39
40
41 #(2)将原始数据集划分成训练集和测试集
42 X ,y=np.split(data,(4,),axis=1) #np.split 按照列(axis=1)进⾏分割,从第四列开始往后的作为y 数据,之前的作为X 数据。函数split(数据,分割位置,轴=1(⽔平分割) or 0(垂直分割))。
43 x=X[:,0:2] #在 X中取前两列作为特征(为了后期的可视化画图更加直观,故只取前两列特征值向量进⾏训练)
44 x_train,x_test,y_train,y_test=ain_test_split(x,y,random_state=1,test_size=0.3)45 #⽤train_test_split将数据随机分为训练集和测试集,测试集占总数据的30%(test_size=0.3),random_state是随机数种⼦
46 #参数解释:
47 #x:train_data:所要划分的样本特征集。
48 #y:train_target:所要划分的样本结果。
49 #test_size:样本占⽐,如果是整数的话就是样本的数量。
50 #random_state:是随机数的种⼦。
51 #(随机数种⼦:其实就是该组随机数的编号,在需要重复试验的时候,保证得到⼀组⼀样的随机数。⽐如你每次都填1,其他参数⼀样的情况下你得到的随机数组是⼀样的。但填0或不填,每次都会不⼀样。
52 #随机数的产⽣取决于种⼦,随机数和种⼦之间的关系遵从以下两个规则:种⼦不同,产⽣不同的随机数;种⼦相同,即使实例不同也产⽣相同的随机数。)
53
54
55 #(3)搭建模型,训练SVM分类器
56 #classifier=svm.SVC(kernel='linear',gamma=0.1,decision_function_shape='ovo',C=0.1)成长的烦恼第七季
57 #kernel='linear'时,为线性核函数,C越⼤分类效果越好,但有可能会过拟合(defaul C=1)。
58 classifier=svm.SVC(kernel='rbf',gamma=0.1,decision_function_shape='ovo',C=0.8)59 #kernel='rbf'(default)时,为⾼斯核函数,gamma值越⼩,分类界⾯越连续;gamma值越⼤,分类界⾯越“散”,分类效果越好,但有可能会过拟合。
60 #decision_function_shape='ovo'时,为one v one分类问题,即将类别两两之间进⾏划分,⽤⼆分类的⽅法模拟多分类的结果。
b s
61 #decision_function_shape='ovr'时,为one v rest分类问题,即⼀个类别与其他类别进⾏划分。
62 #开始训练
63 classifier.fit(x_train,y_train.ravel())64 #调⽤ravel()函数将矩阵转变成⼀维数组
65 #(ravel()函数与flatten()的区别)
66 #两者所要实现的功能是⼀致的(将多维数组降为⼀维),
67 #两者的区别在于返回拷贝(copy)还是返回视图(view),
68 #numpy.flatten() 返回⼀份拷贝,对拷贝所做的修改不会影响(reflects)原始矩阵,
69 #⽽numpy.ravel()返回的是视图(view),会影响(reflects)原始矩阵。
70
71
72 defshow_accuracy(y_hat,y_train,str):73 pass
74
75 #(4)计算svm分类器的准确率
76 print("SVM-输出训练集的准确率为:",classifier.score(x_train,y_train))77 y_hat=classifier.predict(x_train)78
show_accuracy(y_hat,y_train,'训练集')79 print("SVM-输出测试集的准确率为:",classifier.score(x_test,y_test))80
y_hat=classifier.predict(x_test)81 show_accuracy(y_hat,y_test,'测试集')82 #SVM-输出训练集的准确率为: 0.838095238095女生英语名字
83 #SVM-输出测试集的准确率为: 0.777777777778
84
85
86 #查看决策函数,可以通过decision_function()实现。decision_function中每⼀列的值代表距离各类别的距离。
87 #print('decision_function:\n', classifier.decision_function(x_train))
88 print('\npredict:\n', classifier.predict(x_train))89
90
91 #(5)绘制图像
92 #1.确定坐标轴范围,x,y轴分别表⽰两个特征
93 x1_min, x1_max = x[:, 0].min(), x[:, 0].max() #第0列的范围 x[:, 0] ":"表⽰所有⾏,0表⽰第1列
94 x2_min, x2_max = x[:, 1].min(), x[:, 1].max() #第1列的范围 x[:, 0] ":"表⽰所有⾏,1表⽰第2列
95 x1, x2 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j] #⽣成⽹格采样点(⽤meshgrid函数⽣成两个⽹格矩阵X1和X2)
96 grid_test = np.stack((x1.flat, x2.flat), axis=1) #测试点,再通过stack()函数,axis=1,⽣成测试点
97 #.flat 将矩阵转变成⼀维数组 (与ravel()的区别:flatten:返回的是拷贝
98
99 print("grid_test = \n", grid_test)100 #print("x = \n",x)假名标注
101 grid_hat = classifier.predict(grid_test) #预测分类值
102
103 print("grid_hat = \n", grid_hat)104 #print(x1.shape())
105 grid_hat = shape(x1.shape) #使之与输⼊的形状相同
106
107
108 #2.指定默认字体
Params['font.sans-rif'] = [u'SimHei']Params['axes.unicode_minus'] =Fal111
112 #3.绘制
113 cm_light = lors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])114 cm_dark =
gotta have you mp3
116 alpha=0.5
117
118 plt.pcolormesh(x1, x2, grid_hat, cmap=cm_light) #预测值的显⽰
119 #plt.scatter(x[:, 0], x[:, 1], c=y, edgecolors='k', s=50, cmap=cm_dark) # 样本
love is blue120 plt.plot(x[:, 0], x[:, 1], 'o', alpha=alpha, color='blue', markeredgecolor='k')121 plt.scatter(x_test[:, 0], x_test[:, 1], s=120, facecolors='none', zorder=10) #圈中测试集样本
122 plt.xlabel(u'花萼长度', fontsize=13)123 plt.ylabel(u'花萼宽度', fontsize=13)124 plt.xlim(x1_min, x1_max)125
plt.ylim(x2_min, x2_max)126 plt.title(u'鸢尾花SVM⼆特征分类', fontsize=15)127 #id()
128 plt.show()129
130
131
132
133 '''
134 #输出训练集的准确率135 print(classifier.score(x_train,x_test))136
137 #由于准确率表现不直观,可以通过其他⽅式观察结果。138
139 #⾸先将原始结果与训练集预测结果进⾏对⽐:140 y_train_hat=classifier.predict(x_train)141 y_train_1d=shape((-1))142 comp=zip(y_train_1d,y_train_hat) #⽤zip把原始结果和预测结果放在⼀起。显⽰如下:143 print(list(comp))144
145 #同样的,可以⽤训练好的模型对测试集的数据进⾏预测:146 print(classifier.score(x_test,y_test))147
y_test_hat=classifier.predict(x_test)148 y_test_1d=shape((-1))149 comp=zip(y_test_1d,y_test_hat)150
print(list(comp))151
152
153 #还可以通过图像进⾏可视化:154 plt.figure()155 plt.subplot(121)156
plt.scatter(x_train[:,0],x_train[:,1],c=shape((-1)),edgecolors='k',s=50)157 plt.subplot(122)158
plt.scatter(x_train[:,0],x_train[:,1],c=y_shape((-1)),edgecolors='k',s=50)159
160 '''

本文发布于:2023-07-04 04:18:35,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/78/1077272.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:数据   训练   函数   结果   分类   转换
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图