1

I made a function to find the nearest neighbour to a point for a homemade knn classifier.

I did the following:

  1. Defined a function euclid_dist(x,y) to find the distance between two points on a 2-d plane.
  2. Defined a function nearest_neigh(p, points, k=3) to find the k nearest points to the point p among the list point.

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

I sliced the ind array within the points to return the k nearest neighbours.

Expected output:

The function returns the k nearest neighbour.

I hope I haven't over-complicated this question.
xoxoxoxoxoxo
  • 40
  • 2
  • 7

2 Answers2

1

I'm pretty sure this happens because points is a list and not a numpy array. That sort of indexing is not supported for lists. Casting points to an array should fix the problem.

Ralvi Isufaj
  • 442
  • 2
  • 9
0

The problem, as mentioned by Ralvi, is because points is most likely a Python list and not a numpy array. The following code produces no errors:

import numpy as np
import math
from random import randint


def euclidean_distance(point1, point2):
    return math.sqrt(sum(math.pow(a - b, 2) for a, b in zip(point1, point2)))


def nearest_neighbor(p, points, k=3):
    """Return the nearest neighbour of a point"""
    distances = []
    for point in points:
        dist = euclidean_distance(p, point)
        distances.append(dist)

    distances = np.array(distances)
    ind = np.argsort(distances)

    print(p)
    return points[ind[0:k]]

# generate an array of random points
points = 0 + np.random.rand(100, 2) * 50

print(nearest_neighbor(points[randint(0, len(points))], points, k=3))
mahieyin-rahmun
  • 1,486
  • 1
  • 12
  • 20