利用python实现KNN算法
时间: 2024-12-26 09:08:30 浏览: 4
在Python中,可以使用scikit-learn库来实现K-近邻(K-Nearest Neighbors, KNN)算法。KNN是一种简单的监督学习方法,它基于数据点之间的距离来进行预测。下面是基本步骤:
1. 导入必要的库:
```python
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
```
2. 准备数据集(假设X为特征矩阵,y为标签数组):
```python
# 加载数据,例如从csv文件或使用numpy生成
X = ... # 特征数据
y = ... # 标签数据
```
3. 划分训练集和测试集:
```python
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
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
```
阅读全文