繁体   English   中英

反转 numpy 中的非零子矩阵,返回原始形状的矩阵

[英]Invert non-zero submatrix in numpy, returning a matrix of original shape

我有一个矩阵,一些行和列等于零,所以它是不可逆的。
我需要得到一个非零子矩阵的逆矩阵,以便逆矩阵具有与原始矩阵相同的结构。
预期的行为将是这样的:

>>>test
array([[1, 0, 0, 2],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [3, 0, 0, 4]])
>>>get_nonzero(test)
array([[1, 2],
       [3, 4]])
>>>np.linalg.inv(nonzero)
array([[-2. ,  1. ],
       [ 1.5, -0.5]])
>>>restore_shape(inv_matrix)
array([[-2. ,  0. ,  0. ,  1. ],
       [ 0. ,  0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0. ,  0. ],
       [ 1.5,  0. ,  0. , -0.5]])

也许这与我最初通过将某些原始矩阵的行和列归零来获得test矩阵有关,其中所有元素都非零,boolean 索引如下:

>>>bool_index
array([False,  True,  True, False])
>>>original[bool_index, :] = 0
>>>original[:, bool_index] = 0
>>>original
array([[1, 0, 0, 2],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [3, 0, 0, 4]])

I achieved getting non-zero submatrix from original matrix by first converting it to pandas DataFrame and indexing with boolean arrays with .loc like this:

>>>pd.DataFrame(original).loc[~bool_index, ~bool_index].values
array([[1, 2],
       [3, 4]])

但是,我不确定,如何有效地将倒置数组恢复到原始形状。

要使用您建议的 function 格式,并假设您的输入矩阵可以导致 N*N 矩阵,则以下工作:

import numpy as np

def get_nonzero(t1):
    t2 = t1[t1 != 0]
    size = int(np.sqrt(len(t2)))

    return t2.reshape(size, size)

def restore_shape(t1, t3):

    t4 = np.zeros(t1.shape)
    idx_non_zeros = np.nonzero(t1)

    for i, elt in enumerate(t3.flatten()):
        t4[idx_non_zeros[0][i], idx_non_zeros[1][i]] = elt

    return t4

t1 = np.array([[1, 0, 0, 2],
               [0, 0, 0, 0],
               [0, 0, 0, 0],
               [3, 0, 0, 4]])

t2 = get_nonzero(t1)
t3 = np.linalg.inv(t2)
t4 = restore_shape(t1, t3)

但正如评论中提出的那样, np.linalg.pinv(t1)更加优雅和高效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM