knn算法python代码
时间: 2023-07-22 17:21:08 浏览: 68
knn算法python
以下是一个简单的KNN算法Python代码示例:
```python
import numpy as np
# 计算距离函数
def distance(x1, x2):
return np.sqrt(np.sum((x1 - x2)**2))
class KNN:
def __init__(self, k=3):
self.k = k
def fit(self, X, y):
self.X_train = X
self.y_train = y
def predict(self, X):
y_pred = []
for x in X:
# 计算当前点与训练集中所有点的距离
distances = [distance(x, x_train) for x_train in self.X_train]
# 将距离从小到大排序,取前k个点
k_indices = np.argsort(distances)[:self.k]
# 找到这k个点所对应的类别
k_labels = [self.y_train[i] for i in k_indices]
# 将出现次数最多的类别作为预测结果
most_common = max(set(k_labels), key=k_labels.count)
y_pred.append(most_common)
return y_pred
```
使用示例:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建KNN模型
knn = KNN(k=3)
knn.fit(X_train, y_train)
# 进行预测
y_pred = knn.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
注意:这只是一个简单的KNN算法示例,实际应用中可能需要进行更多的数据处理和特征工程。
阅读全文