0
votes

I am using a sparse matrix format implemented in scipy as csr_matrix. I have a mat variable which is in csr_matrix format and all its elements are non-negative. However, when I use mat + mat operation, the non-zero element number decreases which is quite strange to me. What want is a element-wise addition but why the non-element number will decreases as each of the element is non-negative.

Best Regards

2
Your question lacks detail, so in my answer I had to make assumptions. I recommend editing your question to add code demonstrating your problem. That will likely get you better answers. - David Alber

2 Answers

1
votes

The nnz member of csr_matrix in SciPy counts explicit zeros, so depending on how you create your matrix, this may explain what you are observing. You can see this behavior by explicitly setting zeros in a matrix.

>>> from scipy.sparse import csr_matrix
>>> A = csr_matrix((5, 5))
>>> A.nnz
0
>>> A[0, 0] = 0
>>> A.nnz
1
>>> A[1,1] = 0
>>> A.nnz
2

Now when you do an operation that creates a new matrix (such as matrix addition), the explicit zeros are not retained.

>>> B = A + A
>>> B.nnz
0
0
votes

although it might be a bit over kill and not related it may be worth looking into these two libraries

petsc4py

petsc

will just about solve any sparse matrix problem you can think of