Scipy CSR 矩阵逐元素添加



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

在这里,我们要向非零条目添加一个标量,而忽略矩阵 稀疏性,即不要接触零条目。


来自精美的 Scipy 文档(** 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]: 

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


免責聲明

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

我有一个稀疏矩阵,

我想在非零条目中添加一个标量,保留矩阵及其编程表示的稀疏性

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

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

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

最新更新