KDTree中的python点索引

a.s*_*iet 5 python kdtree scipy

给定一个点列表,如何在 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]
Run Code Online (Sandbox Code Playgroud)

我可以做这样的事情:

[tree.query_ball_point(i,r=0) for i in points]

>>> [[1], [8]]
Run Code Online (Sandbox Code Playgroud)

这样做有意义吗?

ali*_*i_m 2

用于cKDTree.query(x, k, ...)查找给定点集的k 个x最近邻点:

distances, indices = tree.query(points, k=1)
print(repr(indices))
# array([1, 8])
Run Code Online (Sandbox Code Playgroud)

在这样的简单情况下,您的数据集和查询点集都很小,并且每个查询点与数据集中的单行相同,因此使用简单的布尔运算进行广播而不是构建会更快并查询 kD 树:

data, points = np.array(data), np.array(points)
indices = (data[..., None] == points.T).all(1).argmax(0)
Run Code Online (Sandbox Code Playgroud)

data[..., None] == points.T广播到(nrows, ndims, npoints)数组,对于较大的数据集,数组的内存很快就会变得昂贵。在这种情况下,您可能会从正常for循环或列表理解中获得更好的性能:

indices = [(data == p).all(1).argmax() for p in points]
Run Code Online (Sandbox Code Playgroud)