2
votes

I'm wondering whether there is a way to simply add a dense vector to all the rows of a sparse matrix represented as a csr_matrixin scipy.sparse and returning a sparse matrix, ie trying to sum only the non zero element of the sparse matrix.

If I do something like this:

import numpy as np
import scipy.sparse as sp
W = sp.csr_matrix(np.array([[0,0,1],[0,1,0]]))
v = np.array([2,3,4])

and then

sum = W + v

sum is obviously a dense matrix but with the zero numbers summed too. While, when I try to do:

b = (W != 0)
s = b.multiply(v)
sum = W + s

I obtain the correct result, but as a dense matrix. b is a sparse matrix, but s is not.

1
I obtain b == True and AttributeError: 'bool' object has no attribute 'multiply'.Fred Foo
which version of python and scipy are you using? I'm using scipy 0.14, numpy 1.8.1 and python 3.4rano
SciPy 0.12 and NumPy 1.7.1. But I see that it works correctly with the latest versions from GitHub.Fred Foo
Do you mean it works as expected from the question, ie that it does not return a sparse matrix?rano
It works as you describe in the question.Fred Foo

1 Answers

2
votes

As I said in the comments, the problem appears in multiply, which should produce a sparse matrix for sparse+dense inputs but doesn't. Convert to a sparse format to avoid that problem:

>>> s = (W != 0).multiply(sp.csr_matrix(v))
>>> W + s
<2x3 sparse matrix of type '<type 'numpy.int64'>'
    with 2 stored elements in Compressed Sparse Row format>