我为一个自制的knn分类器创建了一个函数,用于查找点的最近邻点
euclid_dist(x,y)
,用于查找二维平面上两点之间的距离李>nearest_neigh(p, points, k=3)
,用于在列表point
中查找距离点p
最近的k
点李>查找邻居的功能:
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
points
中切片了ind
数组以返回k
最近的邻居。
函数返回k
最近邻
正如Ralvi所提到的,问题在于
points
很可能是一个Python列表,而不是numpy数组。以下代码不产生错误:我很确定会发生这种情况,因为
points
是一个列表,而不是numpy array
。列表不支持这种索引。将points
强制转换到数组应该可以解决这个问题相关问题 更多 >
编程相关推荐