Scipy CSR 矩阵逐元素相加

Scipy CSR Matrix Element-wise Addition

与 numpy arrays/matrices 不同,CSR 矩阵似乎不允许自动广播。 CSR 实现中有用于逐元素乘法的方法,但没有加法。如何有效地通过标量添加到 CSR 稀疏矩阵?

这里我们想给非零项加上一个标量,不理会矩阵 稀疏性,即不要触摸零条目。


来自 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

所以我尝试了(第一部分是来自参考文档的 "stolen")

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.

我选择这种解释的原因是,向 all 条目添加标量会将稀疏矩阵变成非常密集的矩阵...

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

答案在稀疏矩阵表示的用例中很有用,例如,稀疏测量并且您想更正测量偏差,减去平均值等。所以我将把它留在这里,即使可以判断为有争议。