Home > Mobile >  How to sum a list of sparse matrices?
How to sum a list of sparse matrices?

Time:11-25

I'm trying to figure out how to efficiently sum .csr_matrix sparse matrices stored in a list. Here's the issue:

List_=list_of_sparse matrices
I tried the following
result=np.sum(List_)

But I a getting error!

How can I do it? any help will be much appreciated

CodePudding user response:

You can loop the list:

import numpy as np

List_ = [
    np.matrix([[0,0,0],[0,1,0],[0,0,0]]),
    np.matrix([[0,1,0],[0,0,0],[0,0,0]]),
    np.matrix([[0,0,0],[0,0,0],[0,1,0]]),
]

sum_in = np.matrix(
    [[0,0,0],[0,0,0],[0,0,0]]
)

for mat in List_:
    sum_in  = mat

print(sum_in)

CodePudding user response:

For example you have a list of sparse matrix like this:

from scipy.sparse import csr_matrix
import numpy as np
np.random.seed(111)

List_ = [csr_matrix(np.random.binomial(1,0.5,(2,2))) for i in range(3)]

If your array is huge, you should try not to convert it into dense (memory issues), there is already a addition method, so all you need to do is reduce:

from functools import reduce
result = reduce(lambda x,y:x y,List_)
result.toarray()
array([[1, 0],
       [1, 1]])

As mentioned by @AmmarAslam, you can convert it to dense and sum:

[i.toarray() for i in List_]
[array([[1, 0],
    [0, 1]]),
 array([[0, 0],
        [0, 0]]),
 array([[0, 0],
        [1, 0]])]

Summing this up is a matter of:

np.add.reduce([i.toarray() for i in List_])

array([[1, 0],
       [1, 1]])
  • Related