scipy文件中的稀疏效率警告

hmae6n7t  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(194)

当我尝试计算csc_array的矩阵指数时,我得到了以下错误:

anaconda3/lib/python3.9/site-packages/scipy/sparse/_index.py:103:
SparseEfficiencyWarning: Changing the sparsity structure of a
csc_matrix is expensive. lil_matrix is more efficient.```

  self._set_intXint(row, col, x.flat[0])

产生错误的代码是:

csc_t_M = t_M.tocsc()
sigma = scipy.sparse.linalg.expm(-csc_t_M)

t_M是一个dok_数组。
从错误中看,问题出在scipy.sparse包本身。有人知道如何修复这个问题吗?
非常感谢!

6bc51xsx

6bc51xsx1#

sparse.linalg.expm是一个复杂的函数,使用,如docs的Pade approximation。从探索多年前,我记得它涉及到一个矩阵求逆。
让我们用一个小矩阵来测试它:

In [60]: A = sparse.csr_matrix(np.eye(3))

In [61]: A.A
Out[61]: 
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

使用csr

In [63]: linalg.expm(A)
C:\Users\paul\anaconda3\lib\site-packages\scipy\sparse\linalg\dsolve\linsolve.py:318: SparseEfficiencyWarning: splu requires CSC matrix format
  warn('splu requires CSC matrix format', SparseEfficiencyWarning)
C:\Users\paul\anaconda3\lib\site-packages\scipy\sparse\linalg\dsolve\linsolve.py:215: SparseEfficiencyWarning: spsolve is more efficient when sparse b is in the CSC matrix format
  warn('spsolve is more efficient when sparse b '
Out[63]: 
<3x3 sparse matrix of type '<class 'numpy.float64'>'
    with 3 stored elements in Compressed Sparse Row format>

请注意,警告来自spsolvesplu步骤。
我注意到了警告,却没有得到警告:

In [64]: linalg.expm(A.tocsc())
Out[64]: 
<3x3 sparse matrix of type '<class 'numpy.float64'>'
    with 3 stored elements in Compressed Sparse Column format>

In [65]: _.A
Out[65]: 
array([[2.71828183, 0.        , 0.        ],
       [0.        , 2.71828183, 0.        ],
       [0.        , 0.        , 2.71828183]])

它也适用于密集阵列:

In [66]: linalg.expm(A.A)
Out[66]: 
array([[2.71828183, 0.        , 0.        ],
       [0.        , 2.71828183, 0.        ],
       [0.        , 0.        , 2.71828183]])

如果我尝试更改csc矩阵的元素,则会收到警告:

In [86]: M = sparse.random(100,100,.2,'csc')

In [87]: M[50,50] = 12
C:\Users\paul\anaconda3\lib\site-packages\scipy\sparse\_index.py:82: SparseEfficiencyWarning: Changing the sparsity structure of a csc_matrix is expensive. lil_matrix is more efficient.
  self._set_intXint(row, col, x.flat[0])

相关问题