python KDTree 中的点索引
python point indices in KDTree
给定点列表,如何在 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]]
这样做有意义吗?
使用cKDTree.query(x, k, ...)
找到给定点集x
:
的k个最近邻点
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]
给定点列表,如何在 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]]
这样做有意义吗?
使用cKDTree.query(x, 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]