【问题标题】:Get indices of matrix from upper triangle从上三角形获取矩阵的索引
【发布时间】:2014-01-23 18:07:01
【问题描述】:

我有一个表示为 numpy 数组的对称矩阵,如下例所示:

[[ 1. 0.01735908 0.01628629 0.0183845 0.01678901 0.00990739 0.03326491 0.0167446 ] [ 0.01735908 1. 0.0213712 0.02364181 0.02603567 0.01807505 0.0130358 0.0107082 ] [ 0.01628629 0.0213712 1. 0.01293289 0.02041379 0.01791615 0.00991932 0.01632739] [ 0.0183845 0.02364181 0.01293289 1. 0.02429031 0.01190878 0.02007371 0.01399866] [ 0.01678901 0.02603567 0.02041379 0.02429031 1. 0.01496896 0.00924174 0.00698689] [ 0.00990739 0.01807505 0.01791615 0.01190878 0.01496896 1. 0.0110924 0.01514519] [ 0.03326491 0.0130358 0.00991932 0.02007371 0.00924174 0.0110924 1. 0.00808803] [0.0167446 0.0107082 0.01632739 0.01399866 0.00698689 0.01514519 0.00808803 1.]]

而且我需要在不考虑对角线的情况下找到最大值的索引(行和列)。由于是对称矩阵,我只取了矩阵的上三角形。

ind = np.triu_indices(M_size, 1)

然后是最大值的索引

max_ind = np.argmax(H[ind])

但是 ma​​x_ind 是用 triu_indices 取上三角形后得到的向量的索引,我怎么知道我的值的行和列刚刚发现?

矩阵可以是任意大小,但始终是对称的。您知道实现相同目标的更好方法吗? 谢谢

【问题讨论】:

    标签: python numpy matrix


    【解决方案1】:

    您不能通过使用np.triu 来返回矩阵的副本,其中除上三角以外的所有内容都归零,然后只使用np.argmaxnp.unravel_index 来获取行/列索引吗?

    例子:

    x = np.zeros((10,10))
    x[3, 8] = 1
    upper = np.triu(x, 1)
    idx = np.argmax(upper)
    row, col = np.unravel_index(idx, upper.shape)
    

    这种方法的缺点是它会创建输入矩阵的副本,但它仍然应该比在 Python 中循环遍历元素要快得多。它还假设上三角形的最大值> 0。

    【讨论】:

    • 哇,我发现这是一种更优雅的方式。谢谢!
    • 谢谢,但如果我说实话,我可能会选择 @Bonlenfum 的解决方案而不是我的解决方案——它不涉及创建数组的中间副本,也没有警告说上三角形的最大值必须为正数。
    【解决方案2】:

    您可以使用max_ind 的值作为ind 数据的索引

    max_ind = np.argmax(H[ind])
    Out: 23
    
    ind[0][max_ind], ind[1][max_ind],
    Out: (4, 6)
    

    通过查找整个矩阵中的最大值来验证这一点(并不总是有效——取决于数据):

    np.unravel_index(np.argmax(H), H.shape)
    Out: (4, 6)
    

    【讨论】:

      【解决方案3】:

      可能有一种更简洁的“numpy 方式”来做到这一点,但这是首先想到的:

      answer = None
      biggest = 0
      for r,row in enumerate(matrix):
          i,elem = max(enumerate(row[r+1:]), key=operator.itemgetter(1))
          if elem > biggest:
              biggest, answre = elem, i
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-06
        • 2011-06-16
        • 2021-11-15
        • 1970-01-01
        相关资源
        最近更新 更多