I made a function to find the nearest neighbour to a point for a homemade knn classifier.
I did the following:
- Defined a function
euclid_dist(x,y)
to find the distance between two points on a 2-d plane. - Defined a function
nearest_neigh(p, points, k=3)
to find thek
nearest points to the pointp
among the listpoint
.
Function for finding neighbours:
def neares_neigh(p, points, k=3):
"""Return the nearest neighbour of a point"""
distances = []
for point in points:
dist = euclid_dist(p, point)
distances.append(dist)
distances = np.array(distances)
ind = np.argsort(distances)
return points[ind[0:k]]
The last line return points[ind[0:k]]
returns an error:
TypeError: only integer scalar arrays can be converted to a scalar index
ind
array within the points
to return the k
nearest neighbours.
Expected output:
The function returns the k
nearest neighbour.