NumPy广播:计算两个数组之间的平方差之和 [英] NumPy Broadcasting: Calculating sum of squared differences between two arrays
本文介绍了NumPy广播:计算两个数组之间的平方差之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码.它在Python中永远存在.必须有一种方法可以将该计算结果转换为广播...
I have the following code. It is taking forever in Python. There must be a way to translate this calculation into a broadcast...
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
推荐答案
您可以使用 broadcasted way
,就像这样-
You can use np.einsum
after calculating the differences in a broadcasted way
, like so -
ab = a[:,None,:] - b
out = np.einsum('ijk,ijk->ij',ab,ab)
或使用 'sqeuclidean'
,以根据问题的需要为我们提供平方的欧几里德距离,就像这样-
Or use scipy's cdist
with its optional metric argument set as 'sqeuclidean'
to give us the squared euclidean distances as needed for our problem, like so -
from scipy.spatial.distance import cdist
out = cdist(a,b,'sqeuclidean')
这篇关于NumPy广播:计算两个数组之间的平方差之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文