rano
rano

Reputation: 5676

Add a dense vector to a sparse matrix in scipy (via broadcasting)

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.

Upvotes: 3

Views: 1335

Answers (1)

Fred Foo
Fred Foo

Reputation: 363817

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>

Upvotes: 2

Related Questions