给定一个点列表,如何在KDTree中获得它们的索引?
from scipy import spatial
import numpy as np
#some data
x, y = np.mgrid[0:3, 0:3]
data = zip(x.ravel(), y.ravel())
points = [[0,1], [2,2]]
#KDTree
tree = spatial.cKDTree(data)
# incices of points in tree should be [1,8]我可以做这样的事情:
[tree.query_ball_point(i,r=0) for i in points]
>>> [[1], [8]]这样做有意义吗?
发布于 2015-11-20 19:52:13
使用cKDTree.query(x, k, ...)查找与给定点集最近的k个邻域,x
distances, indices = tree.query(points, k=1)
print(repr(indices))
# array([1, 8])在这种简单的情况下,您的数据集和查询点集都很小,而且每个查询点与数据集中的单个行相同,使用简单的布尔操作来广播而不是构建和查询k-D树会更快:
data, points = np.array(data), np.array(points)
indices = (data[..., None] == points.T).all(1).argmax(0)data[..., None] == points.T向(nrows, ndims, npoints)数组广播,对于较大的数据集,该数组的内存很快就会变得昂贵。在这种情况下,您可以通过正常的for循环或列表理解获得更好的性能:
indices = [(data == p).all(1).argmax() for p in points]https://stackoverflow.com/questions/33823706
复制相似问题