前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python sklearn实现SVM鸢尾花分类

Python sklearn实现SVM鸢尾花分类

作者头像
小嗷犬
发布2022-11-15 16:16:03
8310
发布2022-11-15 16:16:03
举报

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


本文目录


准备

使用到的库:

  • numpy
  • matplotlib
  • sklearn

安装:

代码语言:javascript
复制
pip install numpy
pip install matplotlib
pip install sklearn

数据集: 使用开源数据集“鸢尾花数据集”。包含3种类型数据集,共150条数据;数据包含4项特征,花萼长度、花萼宽度、花瓣长度、花瓣宽度;将80%的数据划分为训练集,20%划分为测试集。 下载地址: https://download.csdn.net/download/qq_63585949/86827472 对于SVM,存在一个分类面,两个点集到此平面的最小距离最大,两个点集中的边缘点到此平面的距离最大。


1.加载相关包

代码语言:javascript
复制
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

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

代码语言:javascript
复制
# ======将字符串转化为整形==============
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:\Users\Marquis\Desktop\iris.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)

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

代码语言:javascript
复制
# 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())  # 训练集特征向量和 训练集目标值

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

代码语言:javascript
复制
# 2 定义模型 SVM模型定义
clf = classifier()
# 3 训练模型
train(clf, x_train, y_train)

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

代码语言:javascript
复制
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)

6.预览图

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-11-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 本文目录
  • 准备
  • 1.加载相关包
  • 2.加载数据、切分数据集
  • 3.构建SVM分类器,训练函数
  • 4.初始化分类器实例,训练模型
  • 5.展示训练结果及验证结果
  • 6.预览图
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档