I'm trying to figure out how to best perform elementwise addition (and subtraction) of a sparse matrix and a sparse vector. I found this trick on SO:
mat = sp.csc_matrix([[1,0,0],[0,1,0],[0,0,1]])
vec = sp.csr_matrix([[1,2,1]])
mat.data += np.repeat(vec.toarray()[0], np.diff(mat.indptr))
But unfortunately it only updates non-zero values:
print(mat.todense())
[[2 0 0]
[0 3 0]
[0 0 2]]
The actual accepted answer on the SO thread:
def sum(X,v):
rows, cols = X.shape
row_start_stop = as_strided(X.indptr, shape=(rows, 2),
strides=2*X.indptr.strides)
for row, (start, stop) in enumerate(row_start_stop):
data = X.data[start:stop]
data -= v[row]
sum(mat,vec.A[0])
Does the same thing. I'm unfortunately out of ideas by now, so I was hoping you could help me figuring out the best way to solve this.
EDIT: I'm expecting it to do the same as a dense version of this would do:
np.eye(3) + np.asarray([[1,2,1]])
array([[ 2., 2., 1.],
[ 1., 3., 1.],
[ 1., 2., 2.]])
Thanks
So your original matrix is sparse, the vector is sparse but in the resulting matrix the columns corresponding to nonzero coordinates in your vector will be dense.
So we may as well materialise those columns as dense matrices