Scipy CSR矩阵元素加法

2024-05-04 07:06:19 发布

您现在位置:Python中文网/ 问答频道 /正文

与numpy数组/矩阵不同,CSR matrix似乎不允许自动广播。在CSR实现中,有一些方法可用于元素级乘法,但不包括加法。如何有效地用标量对CSR稀疏矩阵进行加法运算?在


Tags: 方法numpy元素矩阵数组matrix标量csr
1条回答
网友
1楼 · 发布于 2024-05-04 07:06:19

这里我们想给非零的条目添加一个标量,而不用考虑矩阵 稀疏性,即不要接触零条目。在


来自fine Scipy docs** emphasis **是我的):

Attributes

nnz                   Get the count of explicitly-stored values (nonzeros)  
has_sorted_indices    Determine whether the matrix has sorted indices  
dtype (dtype)         Data type of the matrix  
shape (2-tuple)       Shape of the matrix  
ndim  (int)           Number of dimensions (this is always 2)  
**data                CSR format data array of the matrix** 
indices               CSR format index array of the matrix  
indptr                CSR format index pointer array of the matrix

所以我试过了(第一部分是从参考文档中“偷”来的)

In [18]: from scipy import *

In [19]: from scipy.sparse import *

In [20]: row = array([0,0,1,2,2,2])
    ...: col = array([0,2,2,0,1,2])
    ...: data =array([1,2,3,4,5,6])
    ...: a = csr_matrix( (data,(row,col)), shape=(3,3))
    ...: 

In [21]: a.todense()
Out[21]: 
matrix([[1, 0, 2],
        [0, 0, 3],
        [4, 5, 6]], dtype=int64)

In [22]: a.data += 10

In [23]: a.todense()
Out[23]: 
matrix([[11,  0, 12],
        [ 0,  0, 13],
        [14, 15, 16]], dtype=int64)

In [24]: 

它起作用了。如果保存原始矩阵,则可以使用构造函数 使用修改后的数据数组。在


免责声明

这个答案解决了这个问题的解释

I have a sparse matrix, I want to add a scalar to the non zero entries, preserving the sparseness both of the matrix and of its programmatic representation.

我选择这种解释的理由是,将一个标量添加到所有条目中,会使稀疏矩阵变成非常密集的矩阵。。。在

如果这是正确的解释,我不知道:一方面,OP批准了我的答案(至少今天是2017-07-13),另一方面,在他们问题下面的评论中,他们似乎有不同的看法。在

然而,在稀疏矩阵表示的用例中,答案是有用的,例如,稀疏测量,并且您希望纠正测量偏差,减去平均值等。因此,我将把它留在这里,即使可以判断它是有争议的。在

相关问题 更多 >