可以/不能在压缩稀疏行(CSR)矩阵上使用的numpy函数

问题描述 投票:0回答:1

我是Python的新手,我有一个(可能非常天真)的问题。我有一个CSR(压缩稀疏行)矩阵可以工作(我们将它命名为M),看起来像是为我的矩阵设计的2d numpy数组操作工作的一些函数,而其他一些则没有。

例如,numpy.sum(M, axis=0)工作正常,而numpy.diagonal(M)给出一个错误说{ValueError}diag requires an array of at least two dimensions

那么为什么一个矩阵函数对M起作用而另一个不起作用呢?

一个额外的问题是,如果从上面的numpy.diagonal得到CSR矩阵的对角元素不起作用?

python numpy matrix diagonal
1个回答
1
投票

np.diagonal的代码是:

return asanyarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)

也就是说,它首先尝试将参数转换为数组,例如,如果它是列表列表。但这不是将稀疏矩阵转换为ndarray的正确方法。

In [33]: from scipy import sparse                                               
In [34]: M = sparse.csr_matrix(np.eye(3))                                       
In [35]: M                                                                      
Out[35]: 
<3x3 sparse matrix of type '<class 'numpy.float64'>'
    with 3 stored elements in Compressed Sparse Row format>
In [36]: M.A                                  # right                                  
Out[36]: 
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
In [37]: np.asanyarray(M)                    # wrong                           
Out[37]: 
array(<3x3 sparse matrix of type '<class 'numpy.float64'>'
    with 3 stored elements in Compressed Sparse Row format>, dtype=object)

使用np.diagonal的正确方法是:

In [38]: np.diagonal(M.A)                                                       
Out[38]: array([1., 1., 1.])

但不需要那样做。 M已经有一个diagonal方法:

In [39]: M.diagonal()                                                           
Out[39]: array([1., 1., 1.])

np.sum确实有效,因为它将动作委托给方法(查看其代码):

In [40]: M.sum(axis=0)                                                          
Out[40]: matrix([[1., 1., 1.]])
In [41]: np.sum(M, axis=0)                                                      
Out[41]: matrix([[1., 1., 1.]])

作为一般规则,尝试在稀疏矩阵上使用sparse函数和方法。不要指望numpy功能正常工作。 sparse建立在numpy上,但numpy并不“了解”sparse

© www.soinside.com 2019 - 2024. All rights reserved.