确定稀疏矩阵商

时间:2016-10-14 19:47:56

标签: python performance numpy scipy sparse-matrix

我希望在python 2.7中划分两个sparce matricies,基本上是k = numerator / denominator,结果是类型为sp.csr_matrix的稀疏矩阵。我正在使用scipy as spnumpy as np

为此,我遵循分子的点积和分母的逆的线性格式。这两个项目的格式为sp.csr_matrix(([],([],[])),shape=[R,R])

k本身的计算是

k = sp.csr_matrix(numerator.dot(sp.linalg.inv(denominator)))

执行此操作将返回警告:

SparseEfficiencyWarning: splu requires CSC matrix format
warn('splu requires CSC matrix format', SparseEfficiencyWarning)

上述警告对于确定k作为两个稀疏矩阵之间的商的身份有何意义

有没有更有效的方法在python中生成稀疏矩阵和稀疏矩阵逆的点积(两个稀疏矩阵的商)?

我之前找到了Inverting large sparse matrices with scipy,但我不知道这是否已经过时了。

1 个答案:

答案 0 :(得分:2)

借鉴2013年回答:

In [409]: a=np.random.rand(3,3)
In [410]: A=sparse.csr_matrix(a)
In [411]: np.linalg.inv(a)
Out[411]: 
array([[ 26.11275413,  -4.17749006,  -9.82626551],
       [-37.22611759,   9.38404027,  13.80073216],
       [  7.59314843,  -2.04314605,  -1.58410661]])

np inv不是sparse-aware

In [412]: np.linalg.inv(A) 
 ....
LinAlgError: 0-dimensional array given. Array must be at least two-dimensional

使用from scipy.sparse import linalg

In [414]: linalg.inv(A).A
/usr/lib/python3/dist-packages/scipy/sparse/linalg/dsolve/linsolve.py:243: SparseEfficiencyWarning: splu requires CSC matrix format
  warn('splu requires CSC matrix format', SparseEfficiencyWarning)
/usr/lib/python3/dist-packages/scipy/sparse/linalg/dsolve/linsolve.py:161: SparseEfficiencyWarning: spsolve is more efficient when sparse b is in the CSC matrix format
  'is in the CSC matrix format', SparseEfficiencyWarning)
Out[414]: 
array([[ 26.11275413,  -4.17749006,  -9.82626551],
       [-37.22611759,   9.38404027,  13.80073216],
       [  7.59314843,  -2.04314605,  -1.58410661]])

因此请使用csc格式代替csr

In [415]: A1=sparse.csc_matrix(a)
In [416]: linalg.inv(A1).A
Out[416]: 
array([[ 26.11275413,  -4.17749006,  -9.82626551],
       [-37.22611759,   9.38404027,  13.80073216],
       [  7.59314843,  -2.04314605,  -1.58410661]])

同样的事情,但没有稀疏性警告。在没有详细说明的情况下,inv必须使用迭代列而不是行的方法。它spsolve(A, I) I是一个稀疏的eye矩阵。