关于KNN算法分析鸢尾花数据集

一、关于鸢尾花数据的爬取

很多人在学习KNN分析鸢尾花数据时都疑惑如何获取鸢尾花的数据,这里如果看过我之前有关于爬虫的文章可能就很好理解了,其实这就是一个简单的爬虫操作爬取数据。

下面是对于的相关代码:

import requests
url='https://www.gairuo.com/file/data/dataset/iris.data'
response =requests.get(url=url)
#获得相应对象
page_text=response.text
print(page_text)
#持续化存储
with open('./flowers.html','w',encoding='utf-8')as fp:
    fp.write(page_text)
print('爬取结束')

这边我使用一个html显示鸢尾花数据 ,这边就只截取少量数据部分展示,有兴趣的可以自己复制代码去运行

sepal_length,sepal_width,petal_length,petal_width,species
5.1,3.5,1.4,0.2,setosa
4.9,3.0,1.4,0.2,setosa
4.7,3.2,1.3,0.2,setosa
4.6,3.1,1.5,0.2,setosa
5.0,3.6,1.4,0.2,setosa

 二、KNN代码实现

# KNN
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
# data = load_iris()
url = 'https://www.gairuo.com/file/data/dataset/iris.data'
data = pd.read_csv(url)
data ["species"] = data["species"].map({"setosa":1,"virginica":0,"versicolor":2})
# 删除重复的数据 data.duplicated()用来查看是否有重复的数据 any()进查看重复的
data = data.drop_duplicates()
# 查看各个类别的鸢尾花
data["species"].value_counts()
# KNN
class KNN:
    """
    使用Python实现K近邻算法 实现分类
    """
    def __init__(self,k):
        """
        初始化方法
        :parameter
        :param k:int 邻居的个数
        """
        self.k = k
    def fit(self, X, y):
        """
        训练方法
        :parameter
        :param X:   类数组类型 ,形状为:[样本数量,特征数量]  待训练的样本特征
        :param y:   类数组类型,形状为:[样本数量]    每个样本的目标值 (标签)
        :return:    None
        """
        # 将X,y转换成ndarray数组
        self.X = np.asarray(X)
        self.y = np.asarray(y)
    def predict(self,X):
        """
        根据参数传递的样本,对样本进行预测。
        :parameter
        :param X:   类数组类型 ,形状为:[样本数量,特征数量]  待训练的样本特征
        :return:    数组的类型 (预测的结果)
        """
        X = np.asarray(X)
        result = []
        # 对ndarray数组进行遍历,每次取数组的一行。
        for x in X:
            # 对于测试集的每个样本依次对训练集中的所有样本求距离
            dis = np.sqrt(np.sum((x - self.X) ** 2,axis=1))#axis=1 按照行排列
            # 返回数组排序后,每个元素在原数组中的索引
            index = dis.argsort()
            # 进行截断,只取k个元素[取距离最近的k个元素的索引]
            index = index[:self.k]
            # 返回数组中每个元素出现的次数。元素必须是非负的整数
            count = np.bincount(self.y[index])
            # 返回ndarray数组中最大的元素对应的索引。该索引是我们判定的类别。
            # 最大元素就是出现次数最多的元素
            result.append(count.argmax())
            pass
        return np.asarray(result)
    pass
# 提取出每个类别的鸢尾花数据
t0 = data[data["species"] == 0]
t1 = data[data["species"] == 1]
t2 = data[data["species"] == 2]
# 打乱顺序 每次打乱顺序都是一样的
t0 = t0.sample(len(t0),random_state=0)
t1 = t1.sample(len(t1),random_state=0)
t2 = t2.sample(len(t2),random_state=0)
# 构建训练集和测试集 concat:拼接数组 axis = 0 纵向拼接
train_X = pd.concat([t0.iloc[:40,:-1],t1.iloc[:40,:-1],t2.iloc[:40,:-1]],axis=0)
train_y = pd.concat([t0.iloc[:40,-1],t1.iloc[:40,-1],t2.iloc[:40,-1]],axis=0)
test_X = pd.concat([t0.iloc[40:,:-1],t1.iloc[40:,:-1],t2.iloc[40:,:-1]],axis=0)
test_y = pd.concat([t0.iloc[40:,-1],t1.iloc[40:,-1],t2.iloc[40:,-1]],axis=0)
# 创建KNN对象,进行训练与测试
knn = KNN(k=3)
knn.fit(train_X,train_y)
# 进行测试
result = knn.predict(test_X)
# 预测正确率
print("预测正确率 =",np.sum(result == test_y)/len(result))

三、KNN代码结果

预测正确率 = 0.9629629629629629

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

靳小锅er

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

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

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

打赏作者

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

抵扣说明:

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

余额充值