Python 计算两组 2d 点之间成对距离的替代方法

Python alternative for calculating pairwise distance between two sets of 2d points

在 Matlab 中存在 pdist2 命令。给定矩阵 mx2 和矩阵 nx2,矩阵的每一行代表一个 2d 点。现在我想创建一个 mxn 矩阵,使得 (i,j) 元素表示从 mx2 矩阵的第 i 点到 [=13 的第 j 点的距离=]矩阵。我只是调用命令 pdist2(M,N).

我正在 python 中寻找替代方案。我当然可以编写 2 个 for 循环,但由于我正在使用 2 个 numpy 数组,因此使用 for 循环并不总是最佳选择。 python 宇宙中是否有针对此的优化命令?基本上我要求 python 替代 MATLAB 的 pdist2.

您正在查找 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.        ]]

你应该检查 scikit-learn 包的 pairwise_distances 方法。

sklearn.metrics.pairwise.pairwise_distances(X, Y=None, metric='euclidean', n_jobs=1, **kwds)

更多信息见http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances.html

如果你的矩阵不是太大,这应该不需要使用其他库。如果矩阵很大,这种方法会有点慢并且占用大量内存。

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]])