KNNknn_brute_force函数
时间: 2023-07-30 19:07:12 浏览: 101
KNN algorithm
以下是一个简单的KNN暴力搜索算法的Python实现:
```python
import numpy as np
def knn_brute_force(X_train, y_train, X_test, k):
num_test = X_test.shape[0]
num_train = X_train.shape[0]
dists = np.zeros((num_test, num_train))
for i in range(num_test):
for j in range(num_train):
dists[i, j] = np.sqrt(np.sum((X_test[i] - X_train[j]) ** 2))
y_pred = np.zeros(num_test)
for i in range(num_test):
closest_y = []
closest_y = y_train[np.argsort(dists[i])][:k]
y_pred[i] = np.argmax(np.bincount(closest_y))
return y_pred
```
其中,X_train和y_train是训练集的特征和标签,X_test是测试集的特征,k是选择的最近邻数。
该函数首先计算测试集中每个样本与训练集中每个样本的距离,然后选择距离最小的k个样本,统计它们所属的类别,最终将出现次数最多的类别作为每个测试样本的预测类别。返回预测类别的数组。
阅读全文