4
說我想從scipy.sparse.csr_matrix
中刪除對角線。有沒有這樣做的有效方式?我看到在sparsetools
模塊中有C
函數返回對角線。在scipy中刪除/設置稀疏矩陣的非零對角線元素
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
的代碼?
是'scr_matrix.setdiag'不夠? –
'setdiag'接受一個數組,並設置先前不在矩陣中的元素。因此向矩陣中添加新元素的代價很高,但我沒有對它們進行比較。 – Midnighter
如何創建一個新的稀疏矩陣與你想要刪除的對角線,並減去它?您可能需要運行「壓縮」功能才能完全刪除條目。 – hpaulj