我正在尝试为 IRIS 数据集构建 KNN 算法。首先,我计算了距离并将其存储在一维数组中。但是,我真的很难建立预测功能。因此出现了两个问题:
- 这段代码有什么作用?
classes = y[np.argsort(dist)][:k] - 给定某些要求,我应该如何更改函数的最后一个循环?
def KNN(k, X, y, x):
from scipy.spatial.distance import cdist
"""K nearest neighbors
k: number of nearest neighbors
X: training input locations
y: training labels
x: test input
"""
N, D = X.shape
num_classes = len(np.unique(y))
dist = np.zeros(X.shape[0]) # <-- EDIT THIS to compute the pairwise distance matrix
for i in range(len(dist)):
dist[i] = np.linalg.norm(X[i]-x)
print(dist)
# Next we make the predictions
ypred = np.zeros(num_classes)
classes = y[np.argsort(dist)][:k] # find the labels of the k nearest neighbors
for c in np.unique(classes):
ypred[c] = y[c] # <-- EDIT THIS to compute the correct prediction
print(ypred)
return np.argmax(ypred)
```

