Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting a vector from non-zero values of a sparse matrix

I want to subtract a vector from non zero values of a sparse matrix for e.g.

     [,1] [,2] [,3] [,4]
[1,]    0    0    4    0
[2,]    0    5    0    3
[3,]    1    2    0    0

and here is the vector that i am trying to subtract:

[1 2 3]

so what i need in the end is:

     [,1] [,2] [,3] [,4]
[1,]    0    0    3    0
[2,]    0    3    0    1
[3,]   -2   -1    0    0

I did this by using sparse_matrix.A but it is consuming my memory when I am using the whole data set.

P.S. The dimensions of the matrix are too large and I do not want to use loops!

like image 542
Blend Mexhuani Avatar asked Oct 23 '25 12:10

Blend Mexhuani


1 Answers

Let's begin by setting up the problem, and use csr_matrix from scipy.sparse to build the sparse matrix:

from scipy.sparse import csr_matrix

a = np.array([[0, 0, 4, 0],
              [0, 5, 0, 3],
              [1, 2, 0, 0]])

a_sp = csr_matrix(a, dtype=np.int8)
b = np.array([1,2,3])

We can find the non-zero locations of the sparse matrix with csr_matrix.nonzero, and use the the row coordinates to index the 1d dense array. Then subtract on the corresponding nonzero coordinates by indexing on the sparse matrix:

nz = a_sp.nonzero()
a_sp[nz] -= b[nz[0]]

print(a_sp.toarray())

array([[ 0,  0,  3,  0],
       [ 0,  3,  0,  1],
       [-2, -1,  0,  0]])
like image 52
yatu Avatar answered Oct 25 '25 01:10

yatu



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!