python - 将 scipy 压缩距离矩阵转换为按行读取的较低矩阵

标签 python numpy scipy

我有一个来自 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/

相关文章:

python - 在我的示例中,Pandas 索引不返回行名称

python - PyCharm 警告字符串和字节连接,但一切都是字符串

python - 从稀疏数组的每一行快速拆分列索引数组

python - 将 8 位二进制向量转换为 1 灰度像素

python - 为什么 scipy.ndimage.gaussian_filter 没有内核大小?

python - Windows PC 上的 Python 2.7 中的 `No crypto library available`

python - 为什么在这个链表问题中虚拟节点会发生变化? (python3)

python - 通过 bool 索引数组进行 Numpy 数组赋值

python - 在 Python 中生成数字序列(曲线)

python - CUDA 中的 scipy.interpolate.griddata 等价物