Python sklearn实现SVM鸢尾花分类

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



准备

使用到的库:

  • numpy
  • matplotlib
  • sklearn

安装:

pip install numpy
pip install matplotlib
pip install sklearn

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

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

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


加载相关包

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

加载数据、切分数据集

# ======将字符串转化为整形==============
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)

构建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())  # 训练集特征向量和 训练集目标值

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

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

展示训练结果及验证结果

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)

预览图

SVM鸢尾花分类

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
### 回答1: 尾花分类是机器学习中最为经典和基础的分类问题之一,它的解决方法有很多,其中SVM(Support Vector Machine,支持向量机)是一种比较常用的分类算法。 在Python中,我们可以使用scikit-learn库来实现SVM。具体操作如下: 首先,导入数据集并拆分为训练集和测试集: from sklearn import datasets from sklearn.model_selection import train_test_split # 导入数据集 iris = datasets.load_iris() x = iris.data y = iris.target # 将数据集拆分为训练集和测试集 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0) 然后,使用SVM进行分类: from sklearn import svm # 创建SVM分类器 clf = svm.SVC(kernel='linear', C=1) # 训练模型 clf.fit(x_train, y_train) # 预测结果 y_pred = clf.predict(x_test) 最后,输出分类结果并计算准确率: from sklearn.metrics import accuracy_score print(f"预测结果:{y_pred}") print(f"准确率:{accuracy_score(y_test, y_pred)}") 总之,使用SVM实现尾花分类的过程并不复杂,主要需要掌握数据加载、模型训练和结果预测等基本操作。如果需要提高分类性能,可以尝试调整SVM模型的超参数或使用其他分类算法。 ### 回答2: 尾花分类是机器学习领域中比较常见的一个问题,而支持向量机(SVM)是一种很好的分类器,可以很好地解决这个问题。 下面是使用Python实现尾花分类的步骤: 1.导入库 首先需要导入numpy,pandas和sklearn库。其中,numpy和pandas库用于数据处理,sklearn库则包含了SVM分类器。 2.读取数据 使用read_csv函数读取数据集,将数据集分为X和y两个部分,其中X部分包含了尾花4个特征,y部分包含了尾花的类别。 3.数据预处理 由于数据集中可能存在缺失值或异常值等问题,因此需要进行数据预处理。将数据分为训练集和测试集,然后进行标准化处理(特征缩放),以确保算法的最优效果。 4.SVM分类器模型 定义一个SVM分类器模型,并使用fit函数训练该模型。其中,SVM分类器的参数可以根据具体情况进行调整和优化。 5.测试模型 使用测试集测试模型,并使用accuracy_score函数计算分类器的准确率。 完整代码如下: import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.metrics import accuracy_score # 读取数据 data = pd.read_csv('iris.csv') # 将数据集分为X和y两个部分 X = data.iloc[:, :-1] y = data.iloc[:, -1] # 数据预处理,分为训练集和测试集,并进行标准化处理 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) sc = StandardScaler() X_train_std = sc.fit_transform(X_train) X_test_std = sc.transform(X_test) # SVM分类器模型 svm = SVC(kernel='linear', C=1.0, random_state=0) svm.fit(X_train_std, y_train) # 使用测试集测试模型,并计算分类器的准确率 y_pred = svm.predict(X_test_std) accuracy = accuracy_score(y_test, y_pred) print('Accuracy:', accuracy) 运行代码后,可以得到模型的准确率。这样就完成了使用SVM实现尾花分类的任务。 ### 回答3: 尾花是一个经典的分类问题,它有三种不同的品种,通过花瓣和花萼的大小可以将它们分成不同的类别。SVM是一种流行的机器学习算法,可以用于二分类和多分类问题。 在Python中,我们可以使用sklearn库来实现SVM分类器。首先,我们需要加载数据集。在这个例子中,我们可以使用sklearn内置的尾花数据集。首先,我们要导入数据集和SVM模型: ``` from sklearn import datasets from sklearn import svm ``` 然后,我们可以加载数据集: ``` iris = datasets.load_iris() X = iris.data y = iris.target ``` 数据集包括X和y。X是一组特征值,y是目标值。接下来,我们将数据分成训练集和测试集: ``` X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.4, random_state=0) ``` 现在,我们可以创建一个SVM分类器: ``` clf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train) ``` 这个分类器使用线性核函数和惩罚项C=1训练模型。最后,我们可以对测试集进行预测并计算准确率: ``` from sklearn.metrics import accuracy_score y_pred = clf.predict(X_test) print(accuracy_score(y_test, y_pred)) ``` 以上就是使用SVM实现尾花分类Python代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小嗷犬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值