本文介绍了如何在Scipy中计算稀疏矩阵的广义逆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个稀疏矩阵W,当我使用linalg.pinv(W)时,它会引发一些错误:

I have a sparse matrix W, when I use linalg.pinv(W), it throws some errors:

Traceback (most recent call last):
  File "/Users/ad9075/PycharmProjects/bednmf/test.py", line 14, in testNmfRun
    self.factor = factorization(self.V)
  File "/Users/ad9075/PycharmProjects/bednmf/nmf.py", line 18, in factorization
    W_trans = linalg.pinv(W)
  File "/Library/Python/2.7/site-packages/scipy/linalg/basic.py", line 540, in pinv
    b = np.identity(a.shape[0], dtype=a.dtype)
IndexError: tuple index out of range`

但是当我将其修改为linalg.pinv(W.todense())时,它的效果很好.但是,如果要计算广义逆,真的需要转换稀疏矩阵吗?有人对此有想法吗?

But when I modify it to linalg.pinv(W.todense()), it works well. However, do I really need to convert the sparse matrix if I want to calculate the generaized inverse? Does anyone have ideas about this?

谢谢!

推荐答案

稀疏矩阵的逆(通常是广义逆)通常是稠密的,除非您可以对矩阵的行和列进行置换以使其成为块对角线.

The inverse (and generalized inverse) of a sparse matrix is usually dense, unless you can permute the rows and columns of the matrix so that it becomes block diagonal.

因此,您的问题分为两个部分:(i)查找使其成块对角线的排列,以及(ii)为每个块分别使用linalg.pinv计算广义逆.如果您的矩阵足够小,那么只需先将其转换为密集矩阵,然后计算伪逆数也是有效的.

So your problem splits into two parts: (i) find a permutation that makes it block-diagonal, and (ii) compute the generalized inverse using linalg.pinv separately for each block. If your matrix is small enough, just converting it to a dense matrix first and then computing the pseudoinverse is also efficient.

另一方面,如果您想计算类似"A ^ {-1} x"的内容,则使用gmres或其他迭代程序可能是更有效的解决方案.

If you on the other hand want to compute something like "A^{-1} x", using gmres or some other iterative routine may be a more efficient solution.

这篇关于如何在Scipy中计算稀疏矩阵的广义逆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 06:08