小编典典

NumPy广播:计算两个数组之间的平方差之和

python

我有以下代码。它在Python中永远存在。必须有一种方法可以将此计算结果转换为广播…

def euclidean_square(a,b):
    squares = np.zeros((a.shape[0],b.shape[0]))
    for i in range(squares.shape[0]):
        for j in range(squares.shape[1]):
            diff = a[i,:] - b[j,:]
            sqr = diff**2.0
            squares[i,j] = np.sum(sqr)
    return squares

阅读 356

收藏
2020-12-20

共1个答案

小编典典

您可以np.einsum在计算出的差异后使用broadcasted way,如下所示:

ab = a[:,None,:] - b
out = np.einsum('ijk,ijk->ij',ab,ab)

或使用scipy's cdist其可选的metric参数集,'sqeuclidean'以根据问题的需要给我们平方的欧几里得距离,如下所示-

from scipy.spatial.distance import cdist
out = cdist(a,b,'sqeuclidean')
2020-12-20