2013-09-26 45 views
5

我想知道什麼是用零稀疏矩陣替換不滿足特定條件的行的最佳方法。例如(I使用用於說明普通的數組):將滿足一定條件的scipy.sparse矩陣的行設置爲零

我想要替換的每一行,其總和大於10的零的行

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]]) 

欲更換一個[2]和[ 4]用零,所以我的輸出應該是這樣的:

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]]) 

這是相當簡單的密集矩陣:

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

然而,當我嘗試:

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

我得到這個錯誤:

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

因此,我需要稀疏矩陣不同的解決方案。我想出了這個:

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)) 

這依賴於,如果我們設置單位矩陣對角線的第二和第四個元素爲零,那麼預乘矩陣的行設置爲零的事實。

但是,我覺得有一個更好,更科學的解決方案。有更好的解決方案嗎?

回答

4

不知道是不是很scithonic,但是很多稀疏矩陣的操作最好通過直接訪問膽量來完成。對於你的情況,我個人會這樣做:

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