为什么Scipy的KDTree这么慢?

2024-05-17 13:59:41 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有大约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方法更快,因为它不需要考虑每一对可能的点。在

那么,我误解了什么,能不能快点?在


Tags: 方法infromimportnumpy距离fortime