首页 > 分享 > 利用KNN算法对鸢尾花数据进行分类

利用KNN算法对鸢尾花数据进行分类

鸢尾花数据集下载:

https://blog.csdn.net/wolflikeinnocence/article/details/90140587

KNN代码

'''

Iris数据集三类标签分别为Iris-setosa、Iris-versicolor、Iris-virginica

'''

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

def k_nn(x):

accurary = 0

for i in range(150):

count1 = 0

count2 = 0

count3 = 0

prediction = 0

distance = np.zeros((149, 2))

test = x[i].reshape(1, 5)

train = np.delete(x, i, axis=0)

test1 = test[:, 0:4]

train1 = train[:, 0:4]

for t in range(149):

distance[t, 1] = np.linalg.norm(test1 - train1[t])

distance[t, 0] = train[t, 4]

order = distance[np.lexsort(distance.T)]

for n in range(k):

if order[n, 0] == 1:

count1 += 1

if order[n, 0] == 2:

count2 += 1

if order[n, 0] == 3:

count3 += 1

if count1 >= count2 and count1 >= count3:

prediction = 1

if count2 >= count1 and count2 >= count3:

prediction = 2

if count3 >= count1 and count3 >= count2:

prediction = 3

if prediction == test[0, 4]:

accurary += 1

Accuracy = accurary / 150

return Accuracy

iris = pd.read_csv('Iris.csv', header=None, sep=',')

x = iris.iloc[1:, 1:5]

x = np.array(x, dtype=float)

a = np.full((50, 1), 1)

b = np.full((50, 1), 2)

c = np.full((50, 1), 3)

Res = np.zeros(50)

d = np.vstack((a, b, c))

x = np.hstack((x, d))

for m in range(50):

k = m + 1

Res[m] = k_nn(x)

k_label = np.arange(1, 51, 1)

plt.xlabel('k Value')

plt.ylabel('Accuracy')

plt.ylim((.9, 1))

plt.plot(k_label, Res, 'b')

plt.show()

最后给大家看看不同的K值和正确率的关系图:

相关知识

Knn算法实现鸢尾花分类
实验一:鸢尾花数据集分类
利用KNN对150个实例对花卉进行机器培训
【机器学习】鸢尾花分类
鸢尾花分类
[机器学习基础][笔记] 一、鸢尾花分类
K近邻算法和鸢尾花问题
KNN算法花的分类预测
【机器学习】鸢尾花分类:机器学习领域经典入门项目实战
KNN花卉识别项目练习

网址: 利用KNN算法对鸢尾花数据进行分类 https://m.huajiangbk.com/newsview387260.html

所属分类:花卉
上一篇: 鸢尾花数据SVM分类案列代码讲解
下一篇: 四、鸢尾花分类