Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set rows of scipy.sparse matrix that meet certain condition to zeros

I wonder what is the best way to replaces rows that do not satisfy a certain condition with zeros for sparse matrices. For example (I use plain arrays for illustration):

I want to replace every row whose sum is greater than 10 with a row of zeros

a = np.array([[0,0,0,1,1],
              [1,2,0,0,0],
              [6,7,4,1,0],  # sum > 10
              [0,1,1,0,1],
              [7,3,2,2,8],  # sum > 10 
              [0,1,0,1,2]])

I want to replace a[2] and a[4] with zeros, so my output should look like this:

array([[0, 0, 0, 1, 1],
       [1, 2, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 1, 1, 0, 1],
       [0, 0, 0, 0, 0],
       [0, 1, 0, 1, 2]])

This is fairly straight forward for dense matrices:

row_sum = a.sum(axis=1)
to_keep = row_sum >= 10   
a[to_keep] = np.zeros(a.shape[1]) 

However, when I try:

s = sparse.csr_matrix(a) 
s[to_keep, :] = np.zeros(a.shape[1])

I get this error:

    raise NotImplementedError("Fancy indexing in assignment not "
NotImplementedError: Fancy indexing in assignment not supported for csr matrices.

Hence, I need a different solution for sparse matrices. I came up with this:

def zero_out_unfit_rows(s_mat, limit_row_sum):
    row_sum = s_mat.sum(axis=1).T.A[0]
    to_keep = row_sum <= limit_row_sum
    to_keep = to_keep.astype('int8')
    temp_diag = get_sparse_diag_mat(to_keep)
    return temp_diag * s_mat

def get_sparse_diag_mat(my_diag):
    N = len(my_diag)
    my_diags = my_diag[np.newaxis, :]
    return sparse.dia_matrix((my_diags, [0]), shape=(N,N))

This relies on the fact that if we set 2nd and 4th elements of the diagonal in the identity matrix to zero, then rows of the pre-multiplied matrix are set to zero.

However, I feel that there is a better, more scipynic, solution. Is there a better solution?

like image 306
Akavall Avatar asked Oct 02 '22 20:10

Akavall


1 Answers

Not sure if it is very scithonic, but a lot of the operations on sparse matrices are better done by accessing the guts directly. For your case, I personally would do:

a = np.array([[0,0,0,1,1],
              [1,2,0,0,0],
              [6,7,4,1,0],  # sum > 10
              [0,1,1,0,1],
              [7,3,2,2,8],  # sum > 10 
              [0,1,0,1,2]])
sps_a = sps.csr_matrix(a)

# get sum of each row:
row_sum = np.add.reduceat(sps_a.data, sps_a.indptr[:-1])

# set values to zero
row_mask = row_sum > 10
nnz_per_row = np.diff(sps_a.indptr)
sps_a.data[np.repeat(row_mask, nnz_per_row)] = 0
# ask scipy.sparse to remove the zeroed entries
sps_a.eliminate_zeros()

>>> sps_a.toarray()
array([[0, 0, 0, 1, 1],
       [1, 2, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 1, 1, 0, 1],
       [0, 0, 0, 0, 0],
       [0, 1, 0, 1, 2]])
>>> sps_a.nnz # it does remove the entries, not simply set them to zero
10
like image 199
Jaime Avatar answered Oct 12 '22 12:10

Jaime