I am trying to build the KNN algorithm for IRIS dataset. First, I've computed the distance and stored it in 1d array. However, I am really struggling to build the prediction function. Therefore two questions arise:
- What does this code do?
classes = y[np.argsort(dist)][:k]
- How should I change the last loop of the function given certain requirements?
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)
```