【发布时间】:2020-02-18 01:55:33
【问题描述】:
我有一个需要的线增长算法:
- 计算数组中连续向量之间的距离(欧几里得)
- 插入距离大于特定阈值的新向量
我通常以非常幼稚的方式执行此操作(请参阅下面的代码),并且想知道如何使用 numpy 以最快的方式计算连续向量之间的距离(如果需要,还可以使用 scipy)。
import math
threshold = 10
vectorList = [(0, 10), (4, 8), (14, 14), (16, 19), (35, 16)]
for i in xrange(len(vectorList)):
p1 = vectorList[i]
p2 = vectorList[i+1]
d = math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2)
if d >= threshold:
pmid = ((p1[0] + p2[0]) * .5, (p1[1] + p2[1]) * .5)
vectorList.insert(i+1, pmid)
编辑: 我想出了以下解决方法,但我仍然关心距离计算。
我需要计算一个向量与其在列表中的下一个邻居之间的距离,而不是像我在这里所做的那样计算整个距离矩阵(所有向量彼此相对)。
import numpy as np
vectorList = [(0, 10), (4, 8), (14, 14), (16, 19), (35, 16)]
arr = np.asarray(vectorList).astype(float)
dis = distance.cdist(arr, arr).diagonal(1)
idx = np.where(dis > 10)[0]
vec = (arr[idx] + arr[idx+1]) * .5
arr = np.insert(arr, idx+1, vec, 0)
# output
array([[ 0. , 10. ],[ 4. , 8. ],[ 9. , 11. ],[14. , 14. ],[16. , 19. ],[25.5, 17.5],[35. , 16. ]])
【问题讨论】:
-
这段代码能否可靠地处理
vectorList的增长? -
对于给定的
vectorList转换为二维数组,通过快速 numpy 计算应该很容易得到d(np.diff可能会给你一个起点)。但是逐步添加元素会更难。 -
在插入后的循环中,
i应该是什么,或者更确切地说,p1应该是什么?pmid值?上一次迭代的p2?您可能需要添加另一个元组来测试它。 -
@hpaulj 感谢您的指点和对迟到的回复表示歉意。
np.diff似乎计算向量之间的差异,而不是距离。如果我错了,请纠正我。问题已更新。 -
我的意思是
diff作为起点。您的距离计算使用差异。
标签: python python-2.7 numpy distance insertion