Skip to content
Advertisement

Efficiently accumulating a collection of sparse scipy matrices

I’ve got a collection of O(N) NxN scipy.sparse.csr_matrix, and each sparse matrix has on the order of N elements set. I want to add all these matrices together to get a regular NxN numpy array. (N is on the order of 1000). The arrangement of non-zero elements within the matrices is such that the resulting sum certainly isn’t sparse (virtually no zero elements left in fact).

At the moment I’m just doing

JavaScript

which works but is a bit slow: of course the sheer amount of pointless processing of zeros which is going on there is absolutely horrific.

Is there a better way ? There’s nothing obvious to me in the docs.

Update: as per user545424’s suggestion, I tried the alternative scheme of summing the sparse matrices, and also summing sparse matrices onto a dense matrix. The code below shows all approaches to run in comparable time (Python 2.6.6 on amd64 Debian/Squeeze on a quad-core i7)

JavaScript

and logs out

JavaScript

although you can get one approach or the other to come out ahead by a factor of 2 or so by messing with N,S,D parameters… but nothing like the order of magnitude improvement you’d hope to see from considering the number of zero adds it should be possible to skip.

Advertisement

Answer

I think I’ve found a way to speed it up by a factor of ~10 if your matrices are very sparse.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement