【问题标题】:Get list of X minimum distances by their indices通过索引获取 X 最小距离列表
【发布时间】:2017-06-25 22:57:16
【问题描述】:

我有一个名为 Z 的巨大矩阵(想想 20000 x 1000),我需要从中生成成对距离,因此我目前使用 sklearn.metrics.pairwise.euclidean_distances(Z,Z) 来生成成对距离。

但是,现在我需要搜索结果以找到最小的 X 距离,但我需要它们的索引。

一个例子是:

A = 20000 x 1000 numpy.ndarray
B = sklearn.metrics.pairwise.euclidean_distances(A, A)
C = ((2400,100), (800,900), (29,999)) if X = 3

这样做的最佳方法是什么?我看到了numpy.unravel_index(a.argmax(), a.shape),但我不确定它是否适用于这种情况。

【问题讨论】:

标签: python numpy scikit-learn


【解决方案1】:

您可以使用np.triu_indices 生成对应于压缩距离矩阵条目的索引。

import numpy as np
from scipy.spatial.distance import pdist

# Generate points
Z = np.random.normal(0, 1, (1000, 3))
# Compute euclidean distance
distance = pdist(Z)
# Get the smallest distance
min_distance = np.min(distance)
# Get the indices (k = 1 to omit diagonal entries)
idx = np.asarray(np.triu_indices(len(Z), 1))
# Filter the indices (this is assuming that the minimum distance is not unique)
idx = idx[:, distance == min_distance]

如果你知道只有一个最小距离,你也可以使用

idx = idx[:, np.argmin(distance)]

效率稍高。

编辑:要获得排序后的索引,请尝试以下操作

idx = idx[:, np.argsort(distance)]

【讨论】:

  • 不幸的是,这不适合我。我需要它按最小成对距离排序,然后得到该排序的索引。
猜你喜欢
  • 2013-03-05
  • 2014-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-06
  • 2019-06-06
  • 1970-01-01
  • 2013-12-03
相关资源
最近更新 更多