1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 【统计学习方法】线性可分支持向量机对鸢尾花(iris)数据集进行二分类

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

时间:2019-09-14 04:05:05

相关推荐

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

本文摘要· 理论来源:【统计学习方法】第七章 SVM

· 技术支持:pandas(读csv)、numpy、sklearn.svm、svm思想、matplotlib.pyplot(绘图)

· 代码目的:利用sklearn的svm模型,对鸢尾花数据集进行二分类,同时,对比感知机与线性可分向量机训练效果。

作者:CSDN 征途黯然.

一、鸢尾花(iris)数据集

Iris 鸢尾花数据集是一个经典数据集,在统计学习和机器学习领域都经常被用作示例。数据集内包含 3 类共 150 条记录,每类各 50 个数据,每条记录都有 4 项特征:花萼长度、花萼宽度、花瓣长度、花瓣宽度,可以通过这4个特征预测鸢尾花卉属于(iris-setosa, iris-versicolour, iris-virginica)中的哪一品种。

下载地址:点击此处

二、代码描述

1、首先加载数据,数据特征保留2维,便于我们绘制2d图。

2、然后,测试不同正则化参数C下,线性可分支持向量机训练的效果。

三、效果图

线性可分支持向量机效果:

感知机效果:见【统计学习方法】感知机对鸢尾花(iris)数据集进行二分类

四、python代码(注释详细)

import pandas as pdimport matplotlib.pyplot as pltimport numpy as npfrom 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 = datadef 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,bfor 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和bself.b = self.b + self.l_rate * ywrong_count += 1if wrong_count == 0:is_wrong = Truereturn '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*5plt.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()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。