Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-wise multiplication for sparse matrices in python

I was wondering if there is a operator for element-wise multiplication of rows of a sparse matrix with a vector in scipy.sparse library. Something similar to A*b for numpy arrays? Thanks.

like image 341
user3821329 Avatar asked Oct 17 '25 13:10

user3821329


1 Answers

Use the multiply method:

In [15]: a
Out[15]: 
<3x5 sparse matrix of type '<type 'numpy.int64'>'
    with 5 stored elements in Compressed Sparse Row format>

In [16]: a.A
Out[16]: 
array([[1, 0, 0, 2, 0],
       [0, 0, 3, 0, 0],
       [0, 0, 0, 4, 5]])

In [17]: x
Out[17]: array([ 5, 10, 15, 20, 25])

In [18]: a.multiply(x)
Out[18]: 
matrix([[  5,   0,   0,  40,   0],
        [  0,   0,  45,   0,   0],
        [  0,   0,   0,  80, 125]])

Note that the result is not a sparse matrix if x is a regular numpy array (ndarray). Convert x to a sparse matrix first to get a sparse result:

In [32]: xs = csr_matrix(x)

In [33]: y = a.multiply(xs)

In [34]: y
Out[34]: 
<3x5 sparse matrix of type '<type 'numpy.int64'>'
    with 5 stored elements in Compressed Sparse Row format>

In [35]: y.A
Out[35]: 
array([[  5,   0,   0,  40,   0],
       [  0,   0,  45,   0,   0],
       [  0,   0,   0,  80, 125]])
like image 59
Warren Weckesser Avatar answered Oct 20 '25 13:10

Warren Weckesser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!