【问题标题】:Convert scipy condensed distance matrix to lower matrix read by rows将 scipy 压缩距离矩阵转换为按行读取的下矩阵
【发布时间】:2017-11-06 20:05:56
【问题描述】:

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

我希望在不创建冗余矩阵的情况下将紧凑距离矩阵转换为这种形式。

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    这是一个快速实现 - 但它创建了方形冗余距离矩阵作为中间步骤:

    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的答案给出了相同的函数。)

    【讨论】:

    • 谢谢,我希望避免它,因为我的矩阵很大(10k - 20k 行),但至少我可以使用它。
    • 非常感谢。我早先读过这个问题,因为某种原因我的大脑没有把它放在一起。 span>
    猜你喜欢
    • 2011-08-08
    • 2021-05-19
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    相关资源
    最近更新 更多