这是一个快速实现 - 但它创建了方形冗余距离矩阵作为中间步骤:
In [128]: import numpy as np
In [129]: from scipy.spatial.distance import squareform
c是距离矩阵的冷凝形式:
In [130]: c = np.array([1, 2, 3, 4, 5, 6])
d是冗余方距离矩阵:
In [131]: d = squareform(c)
这是压缩后的下三角距离:
In [132]: d[np.tril_indices(d.shape[0], -1)]
Out[132]: array([1, 2, 4, 3, 5, 6])
这是一种避免形成冗余距离矩阵的方法。 condensed_index(i, j, n) 987654329 @和列j 987654330 j 987654331 @> i,并返回冷凝距离阵列中的相应索引。
In [169]: def condensed_index(i, j, n):
...: return n*i - i*(i+1)//2 + j - i - 1
...:
如上,c 是压缩的距离数组。
In [170]: c
Out[170]: array([1, 2, 3, 4, 5, 6])
In [171]: n = 4
In [172]: i, j = np.tril_indices(n, -1)
请注意,参数在以下呼叫中颠倒:
In [173]: indices = condensed_index(j, i, n)
indices给出了冷凝距离阵列的所需排列。
In [174]: c[indices]
Out[174]: array([1, 2, 4, 3, 5, 6])
(基本上与@ 987654339以this question的答案给出了相同的函数。)