python如何反转稀疏矩阵

时间:2016-11-08 18:55:11

标签: python numpy matrix scipy

我试过scipy。[稀疏] .linalg.inv。它返回矩阵不是方形的错误。

我试过numpy.linalg.inv,它返回一个错误,它显示我传递了一个0维数组。

任何人都可以帮我解决如何反转类型为:

的scipy CSR矩阵
    <10000x31331 sparse matrix of type '<type 'numpy.float64'>'
    with 801667 stored elements in Compressed Sparse Row format>

2 个答案:

答案 0 :(得分:2)

制作一个小数组:

In [435]: A=np.array([[1,0,2,0],[0,1,3,0],[3,0,0,4]])
In [436]: A
Out[436]: 
array([[1, 0, 2, 0],
       [0, 1, 3, 0],
       [3, 0, 0, 4]])
In [437]: np.linalg.pinv(A)
Out[437]: 
array([[ 0.61538462, -0.36923077,  0.04615385],
       [-0.57692308,  0.44615385,  0.06923077],
       [ 0.19230769,  0.18461538, -0.02307692],
       [-0.46153846,  0.27692308,  0.21538462]])

制作稀疏副本:

In [439]: M=sparse.csr_matrix(A)
pinv的{​​p> toarray与以前相同:

In [441]: np.linalg.pinv(M.toarray())
Out[441]: 
array([[ 0.61538462, -0.36923077,  0.04615385],
       [-0.57692308,  0.44615385,  0.06923077],
       [ 0.19230769,  0.18461538, -0.02307692],
       [-0.46153846,  0.27692308,  0.21538462]])

不能直接在稀疏矩阵上使用numpy inv - 因为它不知道如何正确读取该数据结构

In [442]: np.linalg.pinv(M)   
...
LinAlgError: 0-dimensional array given. Array must be at least two-dimensional

有一个稀疏的linalg inv,但它只是spsolve(A,I)。它还警告If the inverse of A is expected to be non-sparse, it will likely be faster to convert A to dense and use scipy.linalg.inv.相同的警告可能适用于pinv或等效物。

我不会在稀疏的linalg列表中看到pinv,但它确实有lsqr

===================

pseudo inverse of sparse matrix in python(2011)

支持伪逆可能密集的想法。但它也提出了使用svds的稀疏解决方案。

另外

How to calculate the generalized inverse of a Sparse Matrix in scipy

答案 1 :(得分:1)

试试看np.linalg.pinv:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.pinv.html

这是矩阵的&#34;广义逆#34;这对矩形(非矩形)矩阵有效。请注意,正如已经指出的那样,矩形矩阵没有唯一的逆矩阵,但是,如果我们施加额外的要求(通过最小二乘法最小化重建误差),我们可以得到一个独特的答案。请小心其解释。

如果您有时间,请在此处阅读更多内容:https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse

此外,由于您使用scipy库中的CSR矩阵,我认为速度很重要,所以请阅读:

The difference of pseudo-inverse between SciPy and Numpy

我不确定是否有类似于pinv的CSR矩阵方法,但如果没有,您可以使用&#34; my_csr_matrix.toarray()&#34;将您的CSR转换为numpy矩阵。但是,考虑开销等(这将取决于应用程序,无论是否正常)。