NumPy 广播:计算两个数组之间的平方差之和 [英] NumPy Broadcasting: Calculating sum of squared differences between two arrays

查看:29
本文介绍了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

推荐答案

您可以使用 np.einsum 在计算 广播方式,像这样-

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)

或者使用scipy 的 cdist 其可选的度量参数设置为 '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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆