knn算法怎么跑python
时间: 2024-06-21 18:02:40 浏览: 86
使用python实现knn算法
K-Nearest Neighbors (KNN) 算法是一种基于实例的学习方法,用于分类和回归任务。在Python中,你可以使用scikit-learn库来轻松实现KNN。以下是使用KNN进行简单分类的一个步骤:
1. 导入所需的库:
```python
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
```
2. 加载数据集(这里以鸢尾花数据集为例):
```python
iris = datasets.load_iris()
X = iris.data
y = iris.target
```
3. 划分训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
4. 创建并训练KNN分类器:
```python
k = 3 # 这里选择3个最近邻居
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train, y_train)
```
5. 预测测试集:
```python
y_pred = knn.predict(X_test)
```
6. 评估模型性能:
```python
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
阅读全文