在 NumPy 中计算距离矩阵的有效方法

问题描述 投票:0回答:3

我有这个示例数组:

In [38]: arr
Out[38]: array([  0,  44, 121, 154, 191])

上面只是一个示例,而我的实际数组大小相当巨大。 那么,计算距离矩阵的有效方法是什么?

结果应该是:

In [41]: res
Out[41]: 
array([[   0,   44,  121,  154,  191],
       [ -44,    0,   77,  110,  147],
       [-121,  -77,    0,   33,   70],
       [-154, -110,  -33,    0,   37],
       [-191, -147,  -70,  -37,    0]])

我写了一个基于

for
循环的实现,它太慢了。出于效率原因可以将其矢量化吗?

python arrays numpy multidimensional-array vectorization
3个回答
2
投票

您可以使用广播:

from numpy import array

arr = array([  0,  44, 121, 154, 191])
arrM = arr.reshape(1, len(arr))
res = arrM - arrM.T

1
投票

subtract
.
outer
,它可以有效地在两个数组之间执行广播减法。

将 ufunc

op
应用于所有对 (a, b),其中 a 在 A 中,b 在 B 中。

设 M = A.ndim,N = B.ndim。那么

op.outer(A, B)
的结果 C 是 维度为 M + N 的数组,使得:

C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] = 
     op(A[i_0, ..., i_{M-1}],B[j_0, ..., j_{N-1}])
np.subtract.outer(arr, arr).T

或者,

arr - arr[:, None] # essentially the same thing as above

array([[   0,   44,  121,  154,  191],
       [ -44,    0,   77,  110,  147],
       [-121,  -77,    0,   33,   70],
       [-154, -110,  -33,    0,   37],
       [-191, -147,  -70,  -37,    0]])

0
投票
def dist_calc(
    arr1: np.ndarray[tuple[int, int], np.dtype[int | float]],
    arr2: np.ndarray[tuple[int, int], np.dtype[int | float]],
) -> np.ndarray[tuple[int, int], np.dtype[float]]:
    """
    calculates euclidean distances between all points in two k-dimensional arrays
    'arr1' and 'arr2'
        :parameter
            - arr1: N x k array
            - arr2: M x k array
        :return
            - dist: M x N array with pairwise distances
    """
    norm_1 = np.sum(arr1 * arr1, axis=1).reshape(1, -1)
    norm_2 = np.sum(arr2 * arr2, axis=1).reshape(-1, 1)

    dist = (norm_1 + norm_2) - 2.0 * np.dot(arr2, arr1.T)
    # necessary due to limited numerical accuracy
    dist[dist < 1.0e-11] = 0.0

    return np.sqrt(dist)

res = dist_calc(arr, arr)

这将是一个更通用的答案,其中数组不必是一维的。

© www.soinside.com 2019 - 2024. All rights reserved.