knn实现python
时间: 2024-11-05 15:00:58 浏览: 11
在Python中,通过scikit-learn库(sklearn.neighbors)实现K近邻(KNN)非常直观。以下是基本步骤:
1. 导入库:
```python
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_iris
```
2. 加载数据集:
```python
# 加载示例数据 - Iris分类数据集
iris = load_iris()
X = iris.data
y = iris.target
```
3. 初始化并训练KNN模型:
```python
k = 3 # 确定K值,例如选择最近的3个邻居
knn_model = KNeighborsClassifier(n_neighbors=k)
knn_model.fit(X, y)
```
4. 预测新样本:
```python
new_sample = [...] # 输入的新数据点
prediction = knn_model.predict([new_sample])
```
5. 可视化和评估:
```python
from matplotlib import pyplot as plt
plt.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis') # 绘制散点图展示数据分布
# 使用交叉验证评估模型性能
from sklearn.model_selection import cross_val_score
cv_scores = cross_val_score(knn_model, X, y, cv=5)
print(f"Cross-validation scores: {cv_scores}")
print(f"Mean accuracy: {np.mean(cv_scores)}")
```
阅读全文