python分类算法_用Python实现KNN分类算法
时间: 2024-01-04 10:03:41 浏览: 106
好的,下面是用 Python 实现 KNN 分类算法的步骤:
1. 导入必要的库
```python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
```
2. 加载数据集
```python
data = pd.read_csv('data.csv')
```
3. 数据预处理
```python
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
```
4. 训练模型
```python
k = 5 # 取 k=5
classifier = KNeighborsClassifier(n_neighbors=k)
classifier.fit(X_train, y_train)
```
5. 预测结果
```python
y_pred = classifier.predict(X_test)
```
6. 计算准确率
```python
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
以上是用 Python 实现 KNN 分类算法的基本步骤,具体实现可以根据实际情况进行调整和优化。
阅读全文