点之间的矢量化/线性代数距离?

时间:2019-01-23 15:46:28

标签: python numpy

假设我有一个点数组,

import numpy as np
pts = np.random.rand(100,3)  # 1000 points, X, Y, Z along second dimension

天真的方法来计算每个点的组合之间的距离涉及到double for循环,并且对于大量的点来说会非常慢,

def euclidian_distance(p1, p2):
    d = p2 - p1
    return np.sqrt(d**2).sum()

out = np.empty((pts.shape[0], pts.shape[0]))
pts_swapped = pts.swapaxes(0,1)
for idx, point in enumerate(pts_swapped):
    for idx2, point_inner in enumerate(pts_swapped):
        out[idx,idx2] = euclidian_distance(point, point_inner)

如何对计算进行矢量化处理?

1 个答案:

答案 0 :(得分:1)

看看scipy.spatial.distance.cdist。我不确定,但是我认为scipy对此进行了很多优化。如果您对两个输入都使用pts数组,那么我假设您会得到一个M x M数组,对角线为零。功能