【问题标题】:Finding index of nearest point in numpy arrays of x and y coordinates在 x 和 y 坐标的 numpy 数组中查找最近点的索引
【发布时间】:2012-06-04 19:43:12
【问题描述】:

我有两个二维 numpy 数组:x_array 包含 x 方向的位置信息,y_array 包含 y 方向的位置。

然后我有一个很长的 x,y 点列表。

对于列表中的每个点,我需要找到最接近该点的位置(在数组中指定)的数组索引。

基于这个问题,我天真地制作了一些有效的代码: Find nearest value in numpy array

import time
import numpy

def find_index_of_nearest_xy(y_array, x_array, y_point, x_point):
    distance = (y_array-y_point)**2 + (x_array-x_point)**2
    idy,idx = numpy.where(distance==distance.min())
    return idy[0],idx[0]

def do_all(y_array, x_array, points):
    store = []
    for i in xrange(points.shape[1]):
        store.append(find_index_of_nearest_xy(y_array,x_array,points[0,i],points[1,i]))
    return store


# Create some dummy data
y_array = numpy.random.random(10000).reshape(100,100)
x_array = numpy.random.random(10000).reshape(100,100)

points = numpy.random.random(10000).reshape(2,5000)

# Time how long it takes to run
start = time.time()
results = do_all(y_array, x_array, points)
end = time.time()
print 'Completed in: ',end-start

我正在对一个大型数据集执行此操作,并且真的想加快一点速度。 谁能优化一下?

谢谢。


更新:解决方案遵循@silvado 和 @justin 的建议(下)

# Shoe-horn existing data for entry into KDTree routines
combined_x_y_arrays = numpy.dstack([y_array.ravel(),x_array.ravel()])[0]
points_list = list(points.transpose())


def do_kdtree(combined_x_y_arrays,points):
    mytree = scipy.spatial.cKDTree(combined_x_y_arrays)
    dist, indexes = mytree.query(points)
    return indexes

start = time.time()
results2 = do_kdtree(combined_x_y_arrays,points_list)
end = time.time()
print 'Completed in: ',end-start

上面的这段代码将我的代码(在 100x100 矩阵中搜索 5000 个点)加快了 100 倍。有趣的是,使用scipy.spatial.KDTree(而不是scipy.spatial.cKDTree)给我的幼稚解决方案提供了相当的时间,所以绝对值得使用cKDTree版本......

【问题讨论】:

  • 只是一个猜测,但也许 k-d 树会有所帮助。不知道Python有没有实现。
  • 无需创建列表和转置“点”。改用数组并分解索引。
  • 来自文档 re KDTree re cKDTree: cKDTree is functionally identical to KDTree. Prior to SciPy v1.6.0, cKDTree had better performance and slightly different functionality but now the two names exist only for backward-compatibility reasons. If compatibility with SciPy < 1.6 is not a concern, prefer KDTree.

标签: python algorithm numpy


【解决方案1】:

如果你可以将你的数据转换成正确的格式,一个快速的方法是使用scipy.spatial.distance中的方法:

http://docs.scipy.org/doc/scipy/reference/spatial.distance.html

特别是pdistcdist 提供了计算成对距离的快速方法。

【讨论】:

  • 我也称之为按摩,它几乎描述了我们如何处理数据。 :D
  • Scipy.spatil.distance 是很棒的工具,但请注意,如果您有很多距离要计算,cKdtree 比 cdist 快得多。
  • 如果我没有被误解,使用 cdist() 或其他 Numpy 方法显示在此答案codereview.stackexchange.com/a/134918/156228
【解决方案2】:

scipy.spatial 也有一个 k-d 树实现:scipy.spatial.KDTree

方法一般是先用点数据建立k-d树。其计算复杂度约为 N log N,其中 N 是数据点的数量。然后可以使用 log N 复杂度来完成范围查询和最近邻搜索。这比简单地循环遍历所有点(复杂度 N)要高效得多。

因此,如果您有重复的范围或最近邻查询,强烈建议使用 k-d 树。

【讨论】:

  • 我仍在测试我的代码,但早期迹象表明使用 scipy.spatial.cKDTree 比我的幼稚方法快大约 100 倍。当我明天有更多时间时,我会发布我的最终代码,并且很可能会接受这个答案(除非在那之前出现更快的方法!)。感谢您的帮助。
  • 好的,使用 scipy.spatial.cKDTree 似乎是要走的路。使用我的测试数据进行测试表明,标准 scipy.spatial.KDTree 与我的幼稚解决方案相比并没有太大/任何改进。
【解决方案3】:

这是一个scipy.spatial.KDTree 示例

In [1]: from scipy import spatial

In [2]: import numpy as np

In [3]: A = np.random.random((10,2))*100

In [4]: A
Out[4]:
array([[ 68.83402637,  38.07632221],
       [ 76.84704074,  24.9395109 ],
       [ 16.26715795,  98.52763827],
       [ 70.99411985,  67.31740151],
       [ 71.72452181,  24.13516764],
       [ 17.22707611,  20.65425362],
       [ 43.85122458,  21.50624882],
       [ 76.71987125,  44.95031274],
       [ 63.77341073,  78.87417774],
       [  8.45828909,  30.18426696]])

In [5]: pt = [6, 30]  # <-- the point to find

In [6]: A[spatial.KDTree(A).query(pt)[1]] # <-- the nearest point 
Out[6]: array([  8.45828909,  30.18426696])

#how it works!
In [7]: distance,index = spatial.KDTree(A).query(pt)

In [8]: distance # <-- The distances to the nearest neighbors
Out[8]: 2.4651855048258393

In [9]: index # <-- The locations of the neighbors
Out[9]: 9

#then 
In [10]: A[index]
Out[10]: array([  8.45828909,  30.18426696])

【讨论】:

  • @lostCrotchet 我想是的。我还用它处理了不止一对数据。例如 (x,y,z,i)
【解决方案4】:

搜索方法有两个阶段:

  1. 建立一个搜索结构,例如KDTree,来自npt 数据点(您的x y
  2. 查找nq查询点。

不同的方法有不同的构建时间和不同的查询时间。 您的选择很大程度上取决于nptnq
scipy cdist 构建时间为 0,但查询时间 ~ npt * nq
KDTree 构建时间很复杂, 查找速度非常快,~ln npt * nq

在常规(曼哈顿)网格上,您可以做得更好:参见(咳咳) find-nearest-value-in-numpy-array.

一点点 testbench: :构建一个 5000 × 5000 2d 点的 KDTree 大约需要 30 秒, 然后查询需要几微秒; scipy cdist 在我的旧 iMac 上,2500 万 × 20 个点(所有对,4G)大约需要 5 秒。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-13
    • 2020-08-23
    • 2013-02-27
    • 1970-01-01
    • 2022-11-17
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多