2014-03-26 142 views
4

說我想從scipy.sparse.csr_matrix中刪除對角線。有沒有這樣做的有效方式?我看到在sparsetools模塊中有C函數返回對角線。在scipy中刪除/設置稀疏矩陣的非零對角線元素

基於其他SO回答herehere我目前的做法是:

def csr_setdiag_val(csr, value=0): 
    """Set all diagonal nonzero elements 
    (elements currently in the sparsity pattern) 
    to the given value. Useful to set to 0 mostly. 
    """ 
    if csr.format != "csr": 
     raise ValueError('Matrix given must be of CSR format.') 
    csr.sort_indices() 
    pointer = csr.indptr 
    indices = csr.indices 
    data = csr.data 
    for i in range(min(csr.shape)): 
     ind = indices[pointer[i]: pointer[i + 1]] 
     j = ind.searchsorted(i) 
     # matrix has only elements up until diagonal (in row i) 
     if j == len(ind): 
      continue 
     j += pointer[i] 
     # in case matrix has only elements after diagonal (in row i) 
     if indices[j] == i: 
      data[j] = value 

然後我用

csr.eliminate_zeros() 

遵循的是最好的,我可以做到不寫我的擁有Cython的代碼?

+0

是'scr_matrix.setdiag'不夠? –

+0

'setdiag'接受一個數組,並設置先前不在矩陣中的元素。因此向矩陣中添加新元素的代價很高,但我沒有對它們進行比較。 – Midnighter

+1

如何創建一個新的稀疏矩陣與你想要刪除的對角線,並減去它?您可能需要運行「壓縮」功能才能完全刪除條目。 – hpaulj

回答

2

根據@ hpaulj的評論,我創建了一個IPython Notebook can be seen on nbviewer。這說明了所有方法中提到以下是最快的(假設mat是一個稀疏矩陣CSR):

mat - scipy.sparse.dia_matrix((mat.diagonal()[scipy.newaxis, :], [0]), shape=(one_dim, one_dim))