我们可以在cdist 结果的平坦距离上使用np.argpartition -
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, 2],
[2, 3]])
在2D 数组上运行示例 -
In [44]: x
Out[44]:
array([[1.25, 1.25],
[1.25, 1.25],
[1.87, 1.87],
[0.62, 0.62],
[0.62, 0.62],
[1.25, 1.25],
[0. , 0. ],
[0.62, 0.62]])
In [45]: m = 2
In [46]: dists
Out[46]:
array([[0. , 0. , 1.58, 1.58, 1.58, 0. , 3.16, 1.58],
[0. , 0. , 1.58, 1.58, 1.58, 0. , 3.16, 1.58],
[0. , 0. , 0. , 3.16, 3.16, 1.58, 4.74, 3.16],
[0. , 0. , 0. , 0. , 0. , 1.58, 1.58, 0. ],
[0. , 0. , 0. , 0. , 0. , 1.58, 1.58, 0. ],
[0. , 0. , 0. , 0. , 0. , 0. , 3.16, 1.58],
[0. , 0. , 0. , 0. , 0. , 0. , 0. , 1.58],
[0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]])
In [47]: idx
Out[47]:
array([[0, 6],
[2, 6]])
请注意,由于argpartition 的工作方式,idx 可能没有按距离排序的索引。为了强迫它这样,我们可以做 -
idx[dists[tuple(idx.T)].argsort()]