我有一个来自 scipy 的压缩距离矩阵,我需要将其传递给一个 C 函数,该函数需要将矩阵转换为按行读取的下三角。例如:
0 1 2 3
0 4 5
0 6
0
它的简写形式是:[1,2,3,4,5,6]
但我需要将它转换成
0
1 0
2 4 0
3 5 6 0
按行读取的下三角是:[1,2,4,3,5,6]
。
我希望在不创建冗余矩阵的情况下将紧凑距离矩阵转换为这种形式。
最佳答案
这是一个快速实现——但它创建了平方冗余距离矩阵作为中间步骤:
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)
取冗余距离矩阵的行i
和列j
,其中j
> 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])
(在 this question 的几个答案中给出了与 condensed_index(i, j, n)
基本相同的函数。)
关于python - 将 scipy 压缩距离矩阵转换为按行读取的较低矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44379284/