【问题标题】:python point indices in KDTreeKDTree中的python点索引
【发布时间】:2016-02-22 18:21:48
【问题描述】:

给定一个点列表,我如何在 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]]

这样做有意义吗?

【问题讨论】:

    标签: python scipy kdtree


    【解决方案1】:

    使用cKDTree.query(x, k, ...) 找到与给定点集x 最接近的k 个邻居:

    distances, indices = tree.query(points, k=1)
    print(repr(indices))
    # array([1, 8])
    

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

    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]
    

    【讨论】:

      猜你喜欢
      • 2021-09-09
      • 2015-01-12
      • 2016-09-23
      • 2018-06-16
      • 2011-08-12
      • 2016-07-20
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      相关资源
      最近更新 更多