首页 > 分享 > 【统计学习方法】线性可分支持向量机对鸢尾花(iris)数据集进行二分类

【统计学习方法】线性可分支持向量机对鸢尾花(iris)数据集进行二分类

import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn.linear_model import Perceptron """自定义感知机模型""" # 数据线性可分,二分类数据 # 此处为一元一次线性方程 class Model: def __init__(self): # 创建指定形状的数组,数组元素以 1 来填充 self.w = np.ones(len(data[0]) - 1, dtype=np.float32) self.b = 0 # 初始w/b的值 self.l_rate = 0.1 # self.data = data def sign(self, x, w, b): y = np.dot(x, w) + b # 求w,b的值 # Numpy中dot()函数主要功能有两个:向量点积和矩阵乘法。 # 格式:x.dot(y) 等价于 np.dot(x,y) ———x是m*n 矩阵 ,y是n*m矩阵,则x.dot(y) 得到m*m矩阵 return y # 随机梯度下降法 # 随机梯度下降法(SGD),随机抽取一个误分类点使其梯度下降。根据损失函数的梯度,对w,b进行更新 def fit(self, X_train, y_train): # 将参数拟合 X_train数据集矩阵 y_train特征向量 is_wrong = False # 误分类点的意思就是开始的时候,超平面并没有正确划分,做了错误分类的数据。 while not is_wrong: wrong_count = 0 # 误分为0,就不用循环,得到w,b for d in range(len(X_train)): X = X_train[d] y = y_train[d] if y * self.sign(X, self.w, self.b) <= 0: # 如果某个样本出现分类错误,即位于分离超平面的错误侧,则调整参数,使分离超平面开始移动,直至误分类点被正确分类。 self.w = self.w + self.l_rate * np.dot(y, X) # 调整w和b self.b = self.b + self.l_rate * y wrong_count += 1 if wrong_count == 0: is_wrong = True return 'Perceptron Model!' # 得分 def score(self): pass # 导入数据集 df = pd.read_csv('./iris/Iris.csv', usecols=[1, 2, 3, 4, 5]) # pandas打印表格信息 # print(df.info()) # pandas查看数据集的头5条记录 # print(df.head()) """绘制训练集基本散点图,便于人工分析,观察数据集的线性可分性""" # 表示绘制图形的画板尺寸为8*5 plt.figure(figsize=(8, 5)) # 散点图的x坐标、y坐标、标签 plt.scatter(df[:50]['SepalLengthCm'], df[:50]['SepalWidthCm'], label='Iris-setosa') plt.scatter(df[50:100]['SepalLengthCm'], df[50:100]['SepalWidthCm'], label='Iris-versicolor') plt.scatter(df[100:150]['SepalLengthCm'], df[100:150]['SepalWidthCm'], label='Iris-virginica') plt.xlabel('SepalLengthCm') plt.ylabel('SepalWidthCm') # 添加标题 '鸢尾花萼片的长度与宽度的散点分布' plt.title('Scattered distribution of length and width of iris sepals.') # 显示标签 plt.legend() plt.show() # 取前100条数据中的:前2个特征+标签,便于训练 data = np.array(df.iloc[:100, [0, 1, -1]]) # 数据类型转换,为了后面的数学计算 X, y = data[:, :-1], data[:, -1] y = np.array([1 if i == 'Iris-setosa' else -1 for i in y]) """自定义感知机模型,开始训练""" perceptron = Model() perceptron.fit(X, y) # 最终参数 print(perceptron.w, perceptron.b) # 绘图 x_points = np.linspace(4, 7, 10) y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1] plt.plot(x_points, y_) plt.scatter(df[:50]['SepalLengthCm'], df[:50]['SepalWidthCm'], label='Iris-setosa') plt.scatter(df[50:100]['SepalLengthCm'], df[50:100]['SepalWidthCm'], label='Iris-versicolor') plt.xlabel('SepalLengthCm') plt.ylabel('SepalWidthCm') # 添加标题 '自定义感知机模型训练结果' plt.title('Training results of Custom perceptron model.') plt.legend() plt.show() """sklearn感知机模型,开始训练""" # 使用训练数据进行训练 clf = Perceptron() # 得到训练结果,权重矩阵 clf.fit(X, y) # Weights assigned to the features.输出特征权重矩阵 # print(clf.coef_) # 超平面的截距 Constants in decision function. # print(clf.intercept_) # 对测试集预测 # print(clf.predict([[6.0, 4.0]])) # 对训练集评分 # print(clf.score(X, y)) # 绘图 x_points = np.linspace(4, 7, 10) y_ = -(clf.coef_[0][0] * x_points + clf.intercept_[0]) / clf.coef_[0][1] plt.plot(x_points, y_) plt.scatter(df[:50]['SepalLengthCm'], df[:50]['SepalWidthCm'], label='Iris-setosa') plt.scatter(df[50:100]['SepalLengthCm'], df[50:100]['SepalWidthCm'], label='Iris-versicolor') plt.xlabel('SepalLengthCm') plt.ylabel('SepalWidthCm') # 添加标题 'sklearn感知机模型训练结果' plt.title('Training results of sklearn perceptron model.') plt.legend() plt.show()

相关知识

【统计学习方法】线性可分支持向量机对鸢尾花(iris)数据集进行二分类
支持向量机&鸢尾花Iris数据集的SVM线性分类练习
利用SVM(支持向量机)分类算法对鸢尾花数据集进行分类
MATLAB实现鸢尾花数据集的支持向量机(SVM)分类
使用Python实现线性支持向量机(SVM)算法及其在数据分类中的应用
日常学习记录——支持向量机、随机森林对鸢尾花数据集进行分类
SVM支持向量机分类鸢尾花数据集iris及代码:精准分类,助力机器学习入门
机器学习实践:基于支持向量机算法对鸢尾花进行分类
【机器学习实战入门项目】基于机器学习的鸢尾花分类项目 Iris Flower Classification Project using Machine Learning【含代码数据集】【亲测有效】
支持向量机的鸢尾花分类设计及实现

网址: 【统计学习方法】线性可分支持向量机对鸢尾花(iris)数据集进行二分类 https://m.huajiangbk.com/newsview2508869.html

所属分类:花卉
上一篇: 如何利用垂直门户提供的数据分析功
下一篇: 第1关:酒店评价数据分析.任务描