【发布时间】:2016-08-29 21:05:24
【问题描述】:
假设我有大约 100 组 100 个点,并且想要找出哪些点在给定距离内。我有两种实现,一种使用 k-d 树,另一种只是获得成对距离:
from scipy.spatial.distance import cdist
from scipy.spatial import KDTree
from itertools import combinations
import numpy
import time
pts = [numpy.random.randn(100,2) for x in range(100)]
start = time.time()
for p1, p2 in combinations(pts,2):
numpy.argwhere(cdist(p1, p2) < 0.5)
print(time.time() - start)
start = time.time()
trees = [KDTree(x) for x in pts]
for p1, p2 in combinations(trees,2):
p1.query_ball_tree(p2,0.5,eps=1)
print(time.time() - start)
在我的机器上 cdist 需要 0.5 秒,而 KDTree 实现需要一整分钟。建造树木需要 0.03 秒。我希望KDTree 方法更快,因为它不需要考虑每一对可能的点。
那么,我误解了什么,这可以更快地完成吗?
【问题讨论】:
-
考虑到您的数据相对较小,构建树是否可能意味着未摊销的开销?在
trees = ...后插入print(time.time() - start)即可了解 -
建树耗时 0.032 秒