我有以下代码。它在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
,就像这样-
ab = a[:,None,:] - b
out = np.einsum('ijk,ijk->ij',ab,ab)
或使用
scipy's cdist
及其可选的度量参数设置为'sqeuclidean'
来为我们的问题提供所需的平方欧几里德距离,如下所示-from scipy.spatial.distance import cdist
out = cdist(a,b,'sqeuclidean')
关于python - NumPy广播: Calculating sum of squared differences between two arrays,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36241608/