如何获得n个点之间距离最大的m对点

假设我在一维空间中定义了以下几点:

x = np.array([[0.70710678],[0.70710678],[0.        ],[1.41421356]])

我想在这n个点之间获得欧氏距离最长的m对点(如果m为1,在这种情况下将为1.4142和0)

我尝试使用:

来获取成对距离
from scipy.spatial.distance import pdist,cdist

cdist(x,x,'seuclidean')

在这一部分中,我不确定其余部分如何做。

shi443213174 回答:如何获得n个点之间距离最大的m对点

我们可以在np.argpartition结果的平坦距离上使用cdist-

dists = np.triu(cdist(x,x,'seuclidean'),1)
s = dists.shape
idx = np.vstack(np.unravel_index(np.argpartition(dists.ravel(),-m)[-m:],s)).T

idx将是最远的m对索引,即idx的每一行将代表x中一对索引。

样品运行-

# with m = 1
In [144]: idx
Out[144]: array([[2,3]])

# with m = 2    
In [147]: idx
Out[147]: 
array([[1,2],[2,3]])

# with m = 3        
In [150]: idx
Out[150]: 
array([[0,3],[1,3]])

2D数组上运行的示例-

In [44]: x
Out[44]: 
array([[1.25,1.25],[1.25,[1.87,1.87],[0.62,0.62],[0.,0.  ],0.62]])

In [45]: m = 2

In [46]: dists
Out[46]: 
array([[0.,0.,1.58,3.16,1.58],4.74,3.16],0.  ]])

In [47]: idx
Out[47]: 
array([[0,6],6]])

请注意,由于argpartition的工作方式,idx可能没有按距离排序的索引。为此,我们可以-

idx[dists[tuple(idx.T)].argsort()]
,

要将每个点与最远的对应点配对,可以使用:

np.dstack((x,x[cdist(x,'seuclidean').argmax(axis=-1)]))

#array([[[0.70710678,0.        ]],#
#       [[0.70710678,#
#       [[0.,1.41421356]],#
#       [[1.41421356,0.        ]]])
本文链接:https://www.f2er.com/3167311.html

大家都在问