【问题标题】:numpy functions that can/cannot be used on a compressed sparse row (CSR) matrix可以/不能用于压缩稀疏行 (CSR) 矩阵的 numpy 函数
【发布时间】:2019-07-27 07:18:50
【问题描述】:

我是 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 矩阵中获取对角线元素?

【问题讨论】:

  • 一般情况下,尽可能使用sparse提供的功能和方法。稀疏矩阵不是ndarray 的子类,因此numpy 函数通常不适用于这些矩阵,尤其是当它们首先尝试将输入转换为数组时,例如np.asarray(yourmatrix).

标签: python numpy matrix sparse-matrix diagonal


【解决方案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

【讨论】:

    猜你喜欢
    • 2015-12-05
    • 2023-03-25
    • 2021-08-21
    • 1970-01-01
    • 2019-03-12
    • 2015-12-30
    • 2016-10-29
    • 2016-10-04
    • 2017-07-07
    相关资源
    最近更新 更多