如何仅使用 numpy 从距离矩阵中提取数据点?

Posted

技术标签:

【中文标题】如何仅使用 numpy 从距离矩阵中提取数据点?【英文标题】:How to extract data points from the distance matrix using numpy only? 【发布时间】:2021-12-16 02:02:53 【问题描述】:

我有 2 组数据点:

A:mx10

B:nx10

A和B中数据点的距离矩阵D:mxn

如何使用距离矩阵 D 提取 A 的 k 行,其中它们与 B 中数据点的距离最小?矩阵的大小应为 nxk。我不想循环遍历矩阵的每一列和每一行,所以我对只使用矩阵的方法感兴趣。

D = np.distance_matrix(A, B)

【问题讨论】:

【参考方案1】:

假设已经给出了完整的数组 D 并且“到 B 的距离”表示“到 B 中所有元素的所有距离中的最小者>",那么它应该是这样的

d = D.min(axis=1)  # m-long vector of distances from points in A to B
ord = d.argsort()  # an array of indices in d sorted by the corresponding values
kD = d[ord[:k],:]  # take first k elements

如果km 小得多,这不是很有效,因为它对所有元素进行排序,而不是只查找kth。但它应该可以解决问题。

【讨论】:

以上是关于如何仅使用 numpy 从距离矩阵中提取数据点?的主要内容,如果未能解决你的问题,请参考以下文章