Python计算两组2D点间的成对距离的替代方案

8
在Matlab中存在pdist2命令。给定矩阵mx2和矩阵nx2,矩阵的每一行表示一个2d点。现在我想创建一个mxn矩阵,使得矩阵的第(i,j)个元素表示mx2矩阵的第i个点到nx2矩阵的第j个点之间的距离。我只需调用pdist2(M,N)命令即可。
我正在寻找Python中的替代方法。当然我可以写两个for循环,但由于我使用的是两个numpy数组,使用for循环并不总是最好的选择。在Python宇宙中是否有优化的命令?基本上我正在寻找MATLAB的pdist2的Python替代方案。

scipy pdist是什么? - andrew_reece
它计算同一矩阵中点之间的成对距离。 - user_1_1_1
1
抱歉,有一段时间没有联系了。cdist 应该可以解决这个问题。 - andrew_reece
3个回答

15
您正在寻找 cdist scipy 函数。它将计算两组 n 维矩阵之间的成对距离(默认为欧几里得距离)。
from scipy.spatial.distance import cdist
import numpy as np

X = np.arange(10).reshape(-1,2)
Y = np.arange(10).reshape(-1,2)

cdist(X, Y)
[[  0.           2.82842712   5.65685425   8.48528137  11.3137085 ]
 [  2.82842712   0.           2.82842712   5.65685425   8.48528137]
 [  5.65685425   2.82842712   0.           2.82842712   5.65685425]
 [  8.48528137   5.65685425   2.82842712   0.           2.82842712]
 [ 11.3137085    8.48528137   5.65685425   2.82842712   0.        ]]

0

0

如果您的矩阵不太大,那么这应该可以在不使用其他库的情况下完成。如果矩阵很大,这种方法将会有点慢且占用内存。

mx2 = np.random.randint(1,9,5)    
nx2 = np.random.randint(1,9,3)    
mx2
Out[308]: array([2, 3, 4, 8, 7])    
nx2
Out[309]: array([3, 2, 2])    
mx2[:,None]-nx2
Out[310]: 
array([[-1,  0,  0],
       [ 0,  1,  1],
       [ 1,  2,  2],
       [ 5,  6,  6],
       [ 4,  5,  5]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接