Python 查找最近邻=,TypeError:只能将整数标量数组转换为标量索引
我为一个自制的knn分类器创建了一个函数,用于查找点的最近邻点 我做了以下工作:Python 查找最近邻=,TypeError:只能将整数标量数组转换为标量索引,python,python-3.x,numpy,knn,numpy-slicing,Python,Python 3.x,Numpy,Knn,Numpy Slicing,我为一个自制的knn分类器创建了一个函数,用于查找点的最近邻点 我做了以下工作: 定义了一个函数euclid_dist(x,y),用于查找二维平面上两点之间的距离 定义了一个函数最近点(p,points,k=3),以在列表点中查找距离点p最近的k 查找邻居的功能: def neares_neigh(p, points, k=3): """Return the nearest neighbour of a point""" distances = [] for point
euclid_dist(x,y)
,用于查找二维平面上两点之间的距离最近点(p,points,k=3)
,以在列表点中查找距离点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]]
最后一行返回点[ind[0:k]
返回一个错误:
TypeError:只能将整数标量数组转换为标量索引
我将ind
数组切片到点
中,以返回k
最近邻。
预期产出:
函数返回k
最近邻
我希望我没有把这个问题复杂化。我很确定会发生这种情况,因为
点
是一个列表,而不是numpy数组
。列表不支持这种索引。将点
投射到数组应该可以解决问题。正如Ralvi所提到的,问题在于点
很可能是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))
或者将ind加入一个列表:ind.tolist()非常感谢