knn算法python实现散点图
时间: 2025-05-22 19:53:42 浏览: 13
### KNN算法实现与散点图绘制
以下是基于Python的KNN算法实现以及通过`matplotlib`和`seaborn`库生成散点图的具体方法:
#### 数据准备
为了演示目的,可以使用经典的鸢尾花数据集(Iris Dataset),该数据集通常被用来测试分类算法的效果。可以通过`sklearn.datasets`模块加载此数据集。
```python
from sklearn import datasets
import pandas as pd
iris = datasets.load_iris()
data = pd.DataFrame(data=iris.data, columns=iris.feature_names)
target = iris.target
```
上述代码片段中,`iris`对象包含了鸢尾花的数据特征及其对应的类别标签[^2]。
---
#### 实现KNN算法
利用`scikit-learn`中的`neighbors.KNeighborsClassifier`来构建KNN模型,并对其进行训练。
```python
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
X_train, X_test, y_train, y_test = train_test_split(
data[['petal length (cm)', 'petal width (cm)']], target,
test_size=0.3, random_state=42)
knn_model = KNeighborsClassifier(n_neighbors=3)
knn_model.fit(X_train, y_train)
predictions = knn_model.predict(X_test)
```
在此部分代码中,选择了花瓣长度和宽度作为两个主要特征来进行建模,并设置了邻居数为3。这一步骤完成了KNN模型的训练过程[^3]。
---
#### 绘制散点图
借助于`matplotlib`和`seaborn`库,可直观展示不同种类鸢尾花之间的分布情况。
```python
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="whitegrid") # 设置Seaborn样式[^1]
plt.figure(figsize=(8, 6))
scatter_plot = sns.scatterplot(
x='petal length (cm)', y='petal width (cm)',
hue=target, palette=sns.color_palette("hls", n_colors=len(set(target))),
data=data, s=100, edgecolor="black"
)
for i in range(len(X_test)):
scatter_plot.text(
X_test.iloc[i]['petal length (cm)'],
X_test.iloc[i]['petal width (cm)'] + 0.03,
f"{y_test.values[i]}->{predictions[i]}",
horizontalalignment='center', size='medium',
color='red' if y_test.values[i] != predictions[i] else 'green'
)
plt.title('Scatter Plot of Iris Data with Predictions')
plt.xlabel('Petal Length (cm)')
plt.ylabel('Petal Width (cm)')
plt.legend(title='Species', loc='upper left') # 添加图例说明
plt.show()
```
这段代码实现了以下功能:
1. 使用`seaborn.scatterplot()`函数创建了一个二维散点图,其中颜色代表不同的鸢尾花品种。
2. 对测试集中每一点进行了标注,显示实际类别到预测类别的映射关系。如果预测错误,则标记为红色;否则为绿色。
3. 调用了`seaborn.set()`设置全局绘图风格以增强视觉效果。
---
#### 总结
以上展示了完整的流程:从数据预处理、建立KNN模型直至最终的结果可视化。这种方法不仅有助于理解KNN的工作原理,还能够清晰地观察到各个样本点的空间位置及其归属类别的情况。
---
阅读全文
相关推荐


















