knn算法python实现
时间: 2024-11-17 11:13:58 浏览: 47
KNN (K-Nearest Neighbors) 算法是一种基于实例的学习方法,在Python中通常通过sklearn库实现。以下是简单的步骤:
1. 导入必要的库:
```python
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
```
2. 准备数据集:数据集应包含特征和标签两部分。例如,你可以使用`load_iris`函数从sklearn加载鸢尾花数据集作为示例。
```python
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
```
3. 划分训练集和测试集:
```python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
4. 创建并训练KNN模型,指定k值(如5):
```python
knn_model = KNeighborsClassifier(n_neighbors=5)
knn_model.fit(X_train, y_train)
```
5. 预测测试集结果:
```python
y_pred = knn_model.predict(X_test)
```
6. 评估模型性能:
```python
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
阅读全文