首页 > 分享 > Python sklearn实现SVM鸢尾花分类

Python sklearn实现SVM鸢尾花分类

2022-11-08 503 发布于四川

版权

举报

版权声明:

本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《 阿里云开发者社区用户服务协议》和 《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写 侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

✅作者简介:人工智能专业本科在读,喜欢计算机与编程,写博客记录自己的学习历程。
个人主页:小嗷犬的博客
个人信条:为天地立心,为生民立命,为往圣继绝学,为万世开太平。
本文内容:Python sklearn实现SVM鸢尾花分类
更多内容请见

Python sklearn实现K-means鸢尾花聚类 Pytorch 基于LeNet的手写数字识别 Pytorch 基于AlexNet的服饰识别(使用Fashion-MNIST数据集)

准备

使用到的库:

numpy matplotlib sklearn

安装:

pip install numpy pip install matplotlib pip install sklearn

AI 代码解读

数据集:
使用开源数据集“鸢尾花数据集”。包含3种类型数据集,共150条数据;数据包含4项特征,花萼长度、花萼宽度、花瓣长度、花瓣宽度;将80%的数据划分为训练集,20%划分为测试集。

下载地址:
https://download.csdn.net/download/qq_63585949/86827472

对于SVM,存在一个分类面,两个点集到此平面的最小距离最大,两个点集中的边缘点到此平面的距离最大。

1.加载相关包

import numpy as np from matplotlib import colors from sklearn import svm from sklearn import model_selection import matplotlib.pyplot as plt import matplotlib as mpl

AI 代码解读

2.加载数据、切分数据集

# ======将字符串转化为整形============== def iris_type(s): it = {b'Iris-setosa': 0, b'Iris-versicolor': 1, b'Iris-virginica': 2} return it[s] # 1 数据准备 # 1.1 加载数据 root = r'C:UsersMarquisDesktopiris.data' # 数据文件路径(需要根据自己数据集的位置修改) data = np.loadtxt(root, dtype=float, # 数据类型 delimiter=',', # 数据分割符 converters={4: iris_type}) # 将第五列使用函数iris_type进行转换 # 1.2 数据分割 x, y = np.split(data, (4, ), axis=1) # 数据分组 第五列开始往后为y 代表纵向分割按列分割 x = x[:, :2] x_train, x_test, y_train, y_test = model_selection.train_test_split( x, y, random_state=1, test_size=0.2)

AI 代码解读

3.构建SVM分类器,训练函数

# SVM分类器构建 def classifier(): clf = svm.SVC(C=0.8, # 误差项惩罚系数 kernel='linear', # 线性核 高斯核 rbf decision_function_shape='ovr') # 决策函数 return clf # 训练模型 def train(clf, x_train, y_train): clf.fit(x_train, y_train.ravel()) # 训练集特征向量和 训练集目标值

AI 代码解读

4.初始化分类器实例,训练模型

# 2 定义模型 SVM模型定义 clf = classifier() # 3 训练模型 train(clf, x_train, y_train)

AI 代码解读

5.展示训练结果及验证结果

def show_accuracy(a, b, tip): acc = a.ravel() == b.ravel() print('%s Accuracy:%.3f' % (tip, np.mean(acc))) # 分别打印训练集和测试集的准确率 score(x_train, y_train)表示输出 x_train,y_train在模型上的准确率 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))) # 原始结果和预测结果进行对比 predict() 表示对x_train样本进行预测,返回样本类别 show_accuracy(clf.predict(x_train), y_train, 'traing data') show_accuracy(clf.predict(x_test), y_test, 'testing data') # 计算决策函数的值 表示x到各个分割平面的距离 print('decision_function:n', clf.decision_function(x_train)) def draw(clf, x): iris_feature = 'sepal length', 'sepal width', 'petal length', 'petal width' # 开始画图 x1_min, x1_max = x[:, 0].min(), x[:, 0].max() x2_min, x2_max = x[:, 1].min(), x[:, 1].max() # 生成网格采样点 x1, x2 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j] # 测试点 grid_test = np.stack((x1.flat, x2.flat), axis=1) 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] print('grid_hat:n', grid_hat) # 使得grid_hat 和 x1 形状一致 grid_hat = grid_hat.reshape(x1.shape) 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) 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=120, facecolor='none', zorder=10) 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('Iris data classification via SVM', fontsize=30) plt.grid() plt.show() # 4 模型评估 print('-------- eval ----------') print_accuracy(clf, x_train, y_train, x_test, y_test) # 5 模型使用 print('-------- show ----------') draw(clf, x)

AI 代码解读

6.预览图

相关知识

SVM实现鸢尾花分类
如何利用SVM算法实现鸢尾花数据集的分类,并使用Matplotlib进行数据的可视化展示?请提供详细的Python代码实现。
作业5:SVM实现鸢尾花分类
卷积神经网络实现鸢尾花数据分类python代码实现
【机器学习】SVM对Iris鸢尾花数据集实现多分类
BPNN、决策树、KNN、SVM分类鸢尾花数据集Python实现
python鸢尾花分类svm测试集
在Python中如何使用SVM算法对鸢尾花数据集进行分类,并用Matplotlib实现数据的可视化展示?请提供具体的步骤和代码示例。
【视觉算法—图像分类】基于SVM实现鸢尾花数据集分类
用svm进行鸢尾花分类

网址: Python sklearn实现SVM鸢尾花分类 https://m.huajiangbk.com/newsview1786888.html

所属分类:花卉
上一篇: 对接第三方聚合支付平台支付宝先用
下一篇: 数据结构23