我有以下代码。它在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
您可以np.einsum在计算出的差异后使用broadcasted way,如下所示:
np.einsum
broadcasted way
ab = a[:,None,:] - b out = np.einsum('ijk,ijk->ij',ab,ab)
或使用scipy's cdist其可选的metric参数集,'sqeuclidean'以根据问题的需要给我们平方的欧几里得距离,如下所示-
scipy's cdist
'sqeuclidean'
from scipy.spatial.distance import cdist out = cdist(a,b,'sqeuclidean')