代码之家  ›  专栏  ›  技术社区  ›  user5054

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

  •  0
  • user5054  · 技术社区  · 7 年前

    我是Python的新手,我有一个问题(可能很幼稚)。我有一个CSR(compressed sparse row)矩阵要处理 M ),看起来有些为2d numpy数组操作而设计的函数对我的矩阵有效,而有些则不行。

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

    那么,为什么一个矩阵函数可以工作呢 M 而另一个没有?

    另外一个问题是,如何从上面给出的CSR矩阵中得到对角线元素 numpy.diagonal 不适用吗?

    0 回复  |  直到 6 年前
        1
  •  1
  •   hpaulj    7 年前

    的代码 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.对角线

    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 功能正常工作。 是建立在 努比 努比 稀疏