【问题标题】:How to get m pair of points among n points that have the largest distance between them如何在它们之间距离最大的n个点中获得m对点
【发布时间】:2020-02-29 16:35:28
【问题描述】:

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

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

从这部分开始,我不知道其余的该怎么做。

【问题讨论】:

    标签: python numpy distance euclidean-distance


    【解决方案1】:

    我们可以在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()]
    

    【讨论】:

    • 如果我的点是二维的:array([[1.246, 1.246], [1.246, 1.246], [1.869, 1.869], [0.623, 0.623], [0.623, 0.623], [1.246, 1.246], [0. , 0. ], [0.623, 0.623]]) 我没有得到最远的 2 对的索引
    • @Azerila 似乎工作正常。添加了Sample run on 2D array 部分。请检查一下。
    【解决方案2】:

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

    np.dstack((x, x[cdist(x,x, 'seuclidean').argmax(axis=-1)]))
    
    #array([[[0.70710678, 0.        ]],
    #
    #       [[0.70710678, 0.        ]],
    #
    #       [[0.        , 1.41421356]],
    #
    #       [[1.41421356, 0.        ]]])
    

    【讨论】:

    • 在输出中,相同的对以不同的顺序重复,我只寻找 m 最长的对
    猜你喜欢
    • 2015-09-03
    • 2016-02-19
    • 2020-01-12
    • 2019-11-07
    • 2020-06-01
    • 2015-07-01
    • 1970-01-01
    • 2021-01-26
    • 2015-07-10
    相关资源
    最近更新 更多