假设我有大约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
方法更快,因为它不需要考虑每一对可能的点。在
那么,我误解了什么,能不能快点?在
它是纯Python。另一种实现,cKDTree,要快得多。在
相关问题 更多 >
编程相关推荐