首页 > 分享 > 【统计学习方法】感知机对鸢尾花(iris)数据集进行二分类

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


· 技术支持:pandas(读csv)、matplotlib(画图)、numpy、sklearn.linear_model.Perceptron(感知机模型)、随机梯度下降思想
· 代码目的:利用手写、sklearn两种感知机模型,对鸢尾花数据集进行二分类

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

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(())

# 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()

1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.100.101.102.103.104.105.106.107.108.109.110.111.112.113.114.115.116.117.118.119.120.121.122.123.

相关知识

【统计学习方法】线性可分支持向量机对鸢尾花(iris)数据集进行二分类
《统计学习方法》第 2 章“感知机”学习笔记
鸢尾花(Iris)数据集入门
利用SVM(支持向量机)分类算法对鸢尾花数据集进行分类
支持向量机&鸢尾花Iris数据集的SVM线性分类练习
RBF神经网络对iris鸢尾花数据集进行分类识别
python实战(一)——iris鸢尾花数据集分类
鸢尾花(iris)数据集
【机器学习】利用KNN对Iris鸢尾花数据集进行分类
日常学习记录——支持向量机、随机森林对鸢尾花数据集进行分类

网址: 【统计学习方法】感知机对鸢尾花(iris)数据集进行二分类 https://m.huajiangbk.com/newsview2513791.html

所属分类:花卉
上一篇: 设计色彩
下一篇: 色彩入门教程:培养孩子对色彩的感