在numpy中找到n个点到m个点的平方距离

mem*_*555 2 python performance numpy euclidean-distance

我有2个numpy数组(比如X和Y),每行代表一个点向量.
我想在X中的每个点到Y中的每个点之间找到平方的欧氏距离(将其称为'dist').
我希望输出为矩阵D,其中D(i,j)是dist(X(i) ),Y(j)).

我有以下python代码基于:http://nonconditional.com/2014/04/on-the-trick-for-computing-the-squared-euclidian-distances-between-two-sets-of-vectors/

def get_sq_distances(X, Y):
    a = np.sum(np.square(X),axis=1,keepdims=1)
    b = np.ones((1,Y.shape[0]))
    c = a.dot(b)
    a = np.ones((X.shape[0],1))
    b = np.sum(np.square(Y),axis=1,keepdims=1).T
    c += a.dot(b)
    c -= 2*X.dot(Y.T)
    return c
Run Code Online (Sandbox Code Playgroud)

我试图避免循环(我应该吗?)并使用矩阵mult来进行快速计算.但我在大型阵列上遇到"内存错误"的问题.也许有更好的方法来做到这一点?

Mad*_*ist 5

Scipy具有cdist完全符合您要求的功能:

from scipy.spatial import distance
distance.cdist(X, Y, 'sqeuclidean')
Run Code Online (Sandbox Code Playgroud)

上面链接的文档有一些很好的例子.