【发布时间】: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.