首页 > 解决方案 > 寻找最近邻=,TypeError:只有整数标量数组可以转换为标量索引

问题描述

我做了一个函数来为自制的 knn 分类器找到一个点的最近邻居。

我做了以下事情:

  1. 定义了一个函数euclid_dist(x,y)来查找二维平面上两点之间的距离。
  2. 定义了一个函数来在列表nearest_neigh(p, points, k=3)中找到k离该点最近的点。ppoint

寻找邻居的功能:

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]]

最后一行return points[ind[0:k]]返回错误: TypeError: only integer scalar arrays can be converted to a scalar index

ind我将数组 切片points以返回k最近的邻居。

预期输出:

该函数返回k最近的邻居。

我希望我没有把这个问题过度复杂化。

标签: pythonpython-3.xnumpyknnnumpy-slicing

解决方案


我很确定会发生这种情况,因为points它是一个列表而不是一个numpy array. 列表不支持这种索引。转换points为数组应该可以解决问题。


推荐阅读