数据集的最小距离

Minimum distance of a dataset

from scipy.spatial.distance import cdist
from sklearn.datasets import make_moons

X, y = make_moons()
cdist(X,X).min(axis=1)

给了我

array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

这不是我想要的。我想要 X 中所有点之间的最小距离,其中 i 不等于 j。当然,如果i=j,那么我会得到0。我怎样才能使用 cdist?

cdist 是计算数组成对距离的过大杀伤力。对于数组,上三角是所有可能距离的最小有意义表示,不包括到自身的 0 距离。方法是使用 pdist:

from scipy.spatial.distance import pdist
from sklearn.datasets import make_moons

X, y = make_moons()
# desired output
pdist(X).min()

它returns一个上三角ndarray是:

Y: ndarray Returns a condensed distance matrix Y. For each i and j (where i<j<m),where m is the number of original observations. The metric dist(u=X[i], v=X[j]) is computed and stored in entry ij.

您可以阅读更多关于压缩矩阵的内容here

时间比较:

%timeit pdist(X)
73 µs ± 825 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit cdist(X,X)
112 µs ± 315 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)