我创建了一个函数,以查找自制knn分类器的点附近。
euclid_dist(x,y)
以查找二维平面上两点之间的距离。nearest_neigh(p, points, k=3)
,以查找列表k
中最接近点p
的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]]
[最后一行return points[ind[0:k]]
返回错误:TypeError: only integer scalar arrays can be converted to a scalar index
ind
中对points
数组进行了切片,以返回k
最近的邻居。该函数返回k
最近的邻居。
我很确定会发生这种情况,因为points
是列表而不是numpy array
。列表不支持这种索引。将points
强制转换为数组应该可以解决问题。
Ralvi提到的问题是,因为points
很可能是Python列表,而不是numpy数组。以下代码不会产生错误:
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))