SVM调用实例——鸢尾花

任务描述:

构建一个模型,根据鸢尾花的花萼和花瓣大小将其分为三种不同的品种。

数据集:

每一行数据由4个特征值1个目标值组成,4个特征值分别为:萼片长度、萼片宽度、花瓣长度、花瓣宽度,目标值为三种不同类别的鸢尾花。

代码实现:

# ! /usr/bin/env python37
# ! -*- coding:utf-8 -*-
# ====#====#====#====
# HomePage:https://www.cnblogs.com/Qzzz/
# FileName: Iris.py
# Version:1.0.5
# ====#====#====#==== #*************导入必要的包***********************
# numpy:用于科学计算
# matplotlib:用于进行可视化
# sklearn:机器学习算法
import numpy as np
from sklearn import model_selection as mo
from sklearn import svm
from sklearn.svm import SVC
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import colors #*************将字符串转为整型,便于数据加载***********************
#在函数中建立了一个对应字典,输入字符串,输出字符串对应的数字
def iris_type(s):
# print(type(s))
it = {b'Iris-setosa':0, b'Iris-versicolor':1, b'Iris-virginica':2}
return it[s]
#加载数据
data_path='./iris.data'
data = np.loadtxt(data_path, #数据文件的路径
dtype = float, #数据类型
delimiter=',', #数据分隔符
converters={4:iris_type}) #将第五列使用函数iris_type进行转换
# print(data)
# print(data.shape)
#数据分割
x,y = np.split(data, #要切分的数组
(4,), #沿轴切分的位置,第5列开始往后为y
axis=1) #1代表纵向分割,按列分割 x = x[:,0:2]
#第一个逗号之前表示行,只有冒号表示所有行,第二个冒号0:2表示0,1两列
#在X中我们取前两列作为特征,为了后面的可视化,原始的四维不好画图,x[:,0:4]代表第一为全取,第二维取0~2
#????剩下两列的数据不做处理????
# print(x)
x_train,x_test,y_train,y_test=mo.train_test_split(x, #所要划分的样本特征集
y, #所要划分的样本结果
random_state=1, #随机数种子确保产生的随机数组相同
test_size=0.3) #测试样本占比 #**********************SVM分类器构建*************************
def classifier():
#clf = svm.SVC(C=0.8, kernel='rbf', gamma=50, decision_function_shape='ovr)
clf = svm.SVC(C=0.5, #误差项惩罚系数,默认值是1
kernel = 'linear', #线性核 kernel='rbf':高斯核
decision_function_shape = 'ovr') #决策函数
return clf clf = classifier() #************************模型训练*****************************
# y_train.ravel() #扁平化操作,将原来的二维数组转换为一维数组
# array([2., 0., 0., 0., 1., 0., 0., 2., 2., 2., 2., 2., 1., 2., 1., 0., 2.,
# 2., 0., 0., 2., 0., 2., 2., 1., 1., 2., 2., 0., 1., 1., 2., 1., 2.,
# 1., 0., 0., 0., 2., 0., 1., 2., 2., 0., 0., 1., 0., 2., 1., 2., 2.,
# 1., 2., 2., 1., 0., 1., 0., 1., 1., 0., 1., 0., 0., 2., 2., 2., 0.,
# 0., 1., 0., 2., 0., 2., 2., 0., 2., 0., 1., 0., 1., 1., 0., 0., 1.,
# 0., 1., 1., 0., 1., 1., 1., 1., 2., 0., 0., 2., 1., 2., 1., 2., 2.,
# 1., 2., 0.])
def train(clf, x_train, y_train):
clf.fit(x_train, #训练及特征向量,fit表示输入数据开始拟合
y_train.ravel()) #训练集目标值扁平化,将原来的二维数组转换为一维数组 train(clf, x_train, y_train) #**************模型评估并判断ab是否相等,计算acc的均值*************
def show_accuracy(a, b, tip):
acc = a.ravel() == b.ravel()
print('%s Accuracy:%.3f' %(tip, np.mean(acc))) def print_accuracy(clf, x_train, y_train, x_test, y_test):
#分别打印训练集和测试集的准确率
print('training prediction:%.3f' %(clf.score(x_train, y_train)))
print('test data prediction:%.3f' %(clf.score(x_test, y_test)))
#原始结果与预测结果进行比对
show_accuracy(clf.predict(x_train), y_train, 'training data')
show_accuracy(clf.predict(x_test), y_test, 'testing data')
#计算决策函数的值,表示x到各分割平面的距离
print('decision_function:\n', clf.decision_function(x_train)) print_accuracy(clf, x_train, y_train, x_test, y_test) #************************模型使用*************************
def draw(clf, x):
iris_feature = 'sepal length', 'sepal width', 'petal lenght', 'petal width'
# 开始画图
x1_min, x1_max = x[:, 0].min(), x[:, 0].max() #第0列的范围
x2_min, x2_max = x[:, 1].min(), x[:, 1].max() #第1列的范围
x1, x2 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j] #生成网格采样点 开始坐标:结束坐标(不包括):步长
#flat将二维数组转换成1个1维的迭代器,然后把x1和x2的所有可能值给匹配成为样本点
grid_test = np.stack((x1.flat, x2.flat), axis=1) #stack():沿着新的轴加入一系列数组,竖着(按列)增加两个数组,grid_test的shape:(40000, 2)
print('grid_test:\n', grid_test)
# 输出样本到决策面的距离
z = clf.decision_function(grid_test)
print('the distance to decision plane:\n', z) grid_hat = clf.predict(grid_test) # 预测分类值 得到【0,0.。。。2,2,2】
print('grid_hat:\n', grid_hat)
grid_hat = grid_hat.reshape(x1.shape) # reshape grid_hat和x1形状一致
#若3*3矩阵e,则e.shape()为3*3,表示3行3列
#light是网格测试点的配色,相当于背景
#dark是样本点的配色
cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
cm_dark = mpl.colors.ListedColormap(['g', 'b', 'r'])
#画出所有网格样本点被判断为的分类,作为背景
plt.pcolormesh(x1, x2, grid_hat, cmap=cm_light) # pcolormesh(x,y,z,cmap)这里参数代入
# x1,x2,grid_hat,cmap=cm_light绘制的是背景。
#squeeze()把y的个数为1的维度去掉,也就是变成一维。
plt.scatter(x[:, 0], x[:, 1], c=np.squeeze(y), edgecolor='k', s=50, cmap=cm_dark) # 样本点
plt.scatter(x_test[:, 0], x_test[:, 1], s=200, facecolor='yellow', zorder=10, marker='+') # 测试点
plt.xlabel(iris_feature[0], fontsize=20)
plt.ylabel(iris_feature[1], fontsize=20)
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.title('svm in iris data classification', fontsize=30)
plt.grid()
plt.show()

Iris_data_analysis的更多相关文章

随机推荐

  1. Git Rebase-提交整洁之道

    git rebase git rebase是一个非常有用的命令,但知道和用的人非常少,今天介绍一下其作用 git rebase -i 作用:常用来合并多个相同目的的提交. 交互式有下面几个命令,常用命 ...

  2. ProxySQL(2):初试读写分离

    文章转载自:https://www.cnblogs.com/f-ck-need-u/p/9278839.html 实现一个简单的读写分离 这里通过一个简单的示例实现ProxySQL的读写分离功能,算是 ...

  3. ERP 系统成功应用取决于哪几个方面?

    ERP系统成功应用主要取决于企业一把手的大力支持.专业的实施顾问.优秀的ERP系统三个方面! 没有企业一把手的大力支持,ERP的应用基本上不可能获得成功.ERP不是简单的信息化工程,它是企业资源计划, ...

  4. P4047 [JSOI2010]部落划分 方法记录

    原题链接 [JSOI2010]部落划分 题目描述 聪聪研究发现,荒岛野人总是过着群居的生活,但是,并不是整个荒岛上的所有野人都属于同一个部落,野人们总是拉帮结派形成属于自己的部落,不同的部落之间则经常 ...

  5. 微软出品自动化神器【Playwright+Java】系列(五) 之 常见点击事件操作

    写在前面 明天就是周五了,这周有那么一两天心情特别不好,真的是做什么都没兴致,所以导致整个人都很丧,什么都不想做. 本打算周一就更新这篇文章的,但由于公司一直加班,每天到家很晚,都是挤时间去学,理解后 ...

  6. Python生成10个八位随机密码

    #生成10个八位随机密码 import random lst1=[ chr(i) for i in range(97,123) ] #生成26为字母列表 lst2=[i for i in range( ...

  7. RAID5 IO处理之写请求代码详解

    我们知道RAID5一个条带上的数据是由N个数据块和1个校验块组成,其校验块由N个数据块通过异或运算得出,这样才能在任意一个成员磁盘失效时通过其他N个成员磁盘恢复出用户写入的数据.这也就要求RAID5条 ...

  8. do-while循环的使用

    一.循环结构的4个要素 ① 初始化条件 ② 循环条件 --->是boolean类型 ③ 循环体 ④ 迭代条件 二.do-while循环结构: ①do{ ③; ④;}while(②); 执行过程: ...

  9. 初始Vue、Vue模板语法、数据绑定(2022/7/3)

    文章目录 1.Vue简介 1.1.Vue的安装使用 1.2.实际的运用案例 1.3.vue开发工具的使用(这个需要在浏览器中安装) 2.初始Vue 2.1 .基础知识 2.1 .代码实例 2.2 .页 ...

  10. Trino Worker 规避 OOM 思路

    背景 Trino 集群如果不做任何配置优化,按照默认配置上线,Master 和 Worker 节点都很容易发生 OOM.本文从 Trino 内存设计出发, 分析 Trino 内存管理机制,到限制与优化 ...