从上三角获取矩阵的索引

Jor*_*ata 4 python numpy matrix

我有一个对称矩阵表示为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)
Run Code Online (Sandbox Code Playgroud)

然后是最大值的索引

max_ind = np.argmax(H[ind])
Run Code Online (Sandbox Code Playgroud)

但是max_ind是使用triu_indices获取上三角形后得到的向量的索引,我怎么知道我刚刚找到的值的行和列是哪一个?

矩阵可以是任何大小,但它总是对称的.你知道更好的方法吗?谢谢

ali*_*i_m 6

难道你不能通过使用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)
Run Code Online (Sandbox Code Playgroud)

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


Bon*_*fum 5

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

max_ind = np.argmax(H[ind])
Out: 23

ind[0][max_ind], ind[1][max_ind],
Out: (4, 6)
Run Code Online (Sandbox Code Playgroud)

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

np.unravel_index(np.argmax(H), H.shape)
Out: (4, 6)
Run Code Online (Sandbox Code Playgroud)