[英]Finding maximum value and their indices in a sparse lil_matrix (Scipy/Python)
[英]How do you store explicit 0 values in a scipy sparse lil_matrix?
scipy.sparse.lil_matrix對象似乎不存儲顯式設置的0值。 其他稀疏矩陣(例如csr_matrix)也可以。
考慮以下示例:
In [1]: from scipy.sparse import lil_matrix
In [2]: import numpy as np
In [3]: x = lil_matrix((5, 5), dtype=np.float32)
In [4]: x[3, 3] = 0
In [5]: x
Out[5]:
<5x5 sparse matrix of type '<class 'numpy.float32'>'
with 0 stored elements in LInked List format>
這是不好的,因為有時圖的元素之間(例如,數據點的重復項)之間的距離為0。 如果我將lil_matrix傳遞到scipy.sparse.csgraph.connected_components,它將檢測到不正確的連接組件數,因為顯式0轉換回“稀疏度”,因此被視為無限距離。
我無法使用csr_matrix,因為將元素分配給它的效率非常低。 但是,它將存儲與lil_matrix不同的顯式設置的0值。 在上面的代碼中,用csr_matrix替換lil_matrix,輸出更改為:
<5x5 sparse matrix of type '<class 'numpy.float32'>'
with 1 stored elements in Compressed Sparse Row format>
有誰知道如何在lil_matrix對象中存儲顯式0值?
謝謝。
lil
__setitem__
使用已編譯的lil_fancy_set
函數。 文檔說:
In [320]: sparse._csparsetools.lil_fancy_set?
Docstring:
Set multiple items to a LIL matrix.
Checks for zero elements and deletes them.
Parameters
----------
M, N, rows, data
LIL matrix data
i_idx, j_idx
Indices of elements to insert to the new LIL matrix.
values
Values of items to set.
Type: builtin_function_or_method
csr
矩陣具有eliminate_zeros
方法:
Signature: M.eliminate_zeros()
Source:
def eliminate_zeros(self):
"""Remove zero entries from the matrix
This is an *in place* operation
"""
M, N = self._swap(self.shape)
_sparsetools.csr_eliminate_zeros(M, N, self.indptr, self.indices,
self.data)
self.prune() # nnz may have changed
File: /usr/local/lib/python3.6/dist-packages/scipy/sparse/compressed.py
Type: method
它還具有sum_duplicates
方法。 在將coo
格式轉換為csr
時使用此方法,並有助於從重疊的子矩陣創建矩陣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.