用python生成knn算法
时间: 2023-07-27 10:25:05 浏览: 88
下面是使用Python编写的KNN算法的基本步骤:
1.导入必要的库:numpy和collections。
``` python
import numpy as np
from collections import Counter
```
2.定义一个函数来计算两个向量之间的距离。这里使用欧几里得距离公式。
``` python
def euclidean_distance(x1, x2):
return np.sqrt(np.sum((x1 - x2)**2))
```
3.定义KNN分类器函数。此函数接受训练数据、测试数据、k值和距离函数作为输入,并返回测试数据的预测标签。
``` python
def knn(X_train, y_train, X_test, k, distance_func):
distances = [distance_func(X_train[i], X_test) for i in range(len(X_train))]
k_indices = np.argsort(distances)[:k]
k_nearest_labels = [y_train[i] for i in k_indices]
most_common = Counter(k_nearest_labels).most_common()
return most_common[0][0]
```
4.测试KNN分类器函数。这里使用一个简单的数据集来测试函数。
``` python
X_train = np.array([[1, 2], [1, 4], [2, 2], [2, 3], [3, 2], [3, 3]])
y_train = np.array([0, 0, 0, 1, 1, 1])
X_test = np.array([2, 1.5])
k = 3
prediction = knn(X_train, y_train, X_test, k, euclidean_distance)
print(prediction)
```
输出将是测试数据的预测标签。
阅读全文