查找最近的邻居=,TypeError:仅整数标量数组可以转换为标量索引

我制作了一个函数,以查找自制knn分类器中与点最近的邻居。

我做了以下事情:

  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.

查找邻居的功能:

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

点数 ķ

预期产量:

The function returns the k nearest neighbour.

评论
  • 空白式
    空白式 回复

    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))
    
  • 小鸡鸡
    小鸡鸡 回复

    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.