KNN实现鸢尾花分类--数据可视化--根据花萼及花瓣分类--sklearn

一、导入相关库

import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import svm
from sklearn import metrics
from sklearn.tree import DecisionTreeClassifier

二、导入数据

1.关于鸢尾花的数据

在这里插入图片描述
一共有150个数据

2.删除Id(不需要的)数据

iris.drop('Id',axis=1,inplace=True)

3.分别利用花萼和花瓣的特征

petal=iris[['PetalLengthCm','PetalWidthCm','Species']]
sepal=iris[['SepalLengthCm','SepalWidthCm','Species']]

三、训练集及测试集

1.花瓣

#花萼
train_p,test_p=train_test_split(petal,test_size=0.3,random_state=0)
train_x_p=train_p[['PetalWidthCm','PetalLengthCm']]
train_y_p=train_p.Species
test_x_p=test_p[['PetalWidthCm','PetalLengthCm']]
test_y_p=test_p.Species

2.花萼

train_s,test_s=train_test_split(sepal,test_size=0.3,random_state=0)
train_x_s=train_s[['SepalWidthCm','SepalLengthCm']]
train_y_s=train_s.Species
test_x_s=test_s[['SepalWidthCm','SepalLengthCm']]
test_y_s=test_s.Species

四、KNN算法

1.花瓣

model=KNeighborsClassifier()
model.fit(train_x_p,train_y_p)
prediction=model.predict(test_x_p)
print('The accuracy of the Petal is:',metrics.accuracy_score(prediction,test_y_p))

2.花萼

model=KNeighborsClassifier()
model.fit(train_x_s,train_y_s)
prediction=model.predict(test_x_s)
print('The accuracy of the Sepal is:',metrics.accuracy_score(prediction,test_y_s))

3.准确度结果

在这里插入图片描述

五、数据可视化

1.散点图

(1) 花萼

#花萼长度和宽度的关系,散点图
fig=iris[iris.Species=='Iris-setosa'].plot(kind='scatter',x='SepalLengthCm',y='SepalWidthCm',color='orange',label='Setosa')
iris[iris.Species=='Iris-versicolor'].plot(kind='scatter',x='SepalLengthCm',y='SepalWidthCm',color='blue',label='versicolor',ax=fig)
iris[iris.Species=='Iris-virginica'].plot(kind='scatter',x='SepalLengthCm',y='SepalWidthCm',color='green',label='virginica',ax=fig)
fig.set_xlabel("Sepal Length")
fig.set_ylabel("Sepal Width")
fig.set_title("Sepal Length VS Width")
fig=plt.gcf()
fig.set_size_inches(10,6)
plt.show()

在这里插入图片描述

(2) 花瓣

#花瓣的长度和宽度的关系,散点图
fig=iris[iris.Species=='Iris-setosa'].plot.scatter(x='PetalLengthCm',y='PetalWidthCm',color='orange',label='Setosa')
fig=iris[iris.Species=='Iris-versicolor'].plot.scatter(x='PetalLengthCm',y='PetalWidthCm',color='blue',label='versicolor',ax=fig)
fig=iris[iris.Species=='Iris-virginica'].plot.scatter(x='PetalLengthCm',y='PetalWidthCm',color='green',label='virginica',ax=fig)
fig.set_xlabel("Petal Length")
fig.set_ylabel("Petal Width")
fig.set_title("Petal Length VS Width")
fig=plt.gcf()
fig.set_size_inches(10,6)
plt.show()

在这里插入图片描述

2.直方图

#iris长度和宽度的分布,绘制直方图
iris.hist(edgecolor='black',linewidth=1.2)
fig=plt.gcf()
fig.set_size_inches(12,6)
plt.show()

在这里插入图片描述

3.小提琴图

#iris长度与宽度跟种类的关系,小提琴图
#小提琴图展示了数据随种类的长度跟密度。越窄的部分说明密度较低,越宽的部分说明数据密度高
plt.figure(figsize=(12,6))
plt.subplot(2,2,1)
sns.violinplot(x='Species',y='PetalLengthCm',data=iris)
plt.subplot(2,2,2)
sns.violinplot(x='Species',y='PetalWidthCm',data=iris)
plt.subplot(2,2,3)
sns.violinplot(x='Species',y='SepalLengthCm',data=iris)
plt.subplot(2,2,4)
sns.violinplot(x='Species',y='SepalWidthCm',data=iris)
plt.show()

在这里插入图片描述

4.相关热力图

#相关性热力图
plt.figure(figsize=(12,6))
sns.heatmap(iris.corr(),annot=True,cmap='cubehelix_r')
plt.show()

在这里插入图片描述

KNN算法原理总结:K近邻算法,给定一个训练数据集,对新的输入实例,在训练数据集中找到与该实例最近邻的K(自己确定)个实例,这K个实例的多数属于某类,就把该输入实例分类到这个类(label)下

  • 8
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
KNN算法对鸢尾花数据进行分类的结果可以通过可视化的方式来展示,以更直观地观察模型的分类效果。以下是一个简单的Python代码示例,实现KNN算法鸢尾花数据集分类可视化: ```python import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier # 加载数据集 iris = load_iris() # 取两个特征值进行可视化 X = iris.data[:, :2] y = iris.target # 训练模型 k = 5 knn = KNeighborsClassifier(n_neighbors=k) knn.fit(X, y) # 可视化分类结果 h = 0.02 x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5 y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.figure(1, figsize=(8, 6)) plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) # 绘制训练集样本点 plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k', cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.title('KNN classification of iris dataset') plt.show() ``` 在上述代码中,我们取数据集中的前两个特征值进行可视化,使用了meshgrid函数生成网格点,用predict函数对网格点进行预测,最后将预测结果进行可视化。此外,我们还绘制了训练集样本点,并设置了横纵坐标轴的标签、范围和标题。运行以上代码,我们可以看到KNN算法鸢尾花数据集分类可视化结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值