簡體   English   中英

Python Scipy如何從csr_matrix遍歷上/下三角部分非零

[英]Python Scipy How to traverse upper/lower trianglar portion non-zeros from csr_matrix

我有一個非常稀疏的矩陣(相似性矩陣),尺寸為300k * 300k。 為了找出用戶之間相對較大的相似性,我只需要矩陣的上/下三角部分。 那么,如何有效地獲取值大於閾值的用戶坐標呢? 謝謝。

怎么樣

sparse.triu(M)

如果M

In [819]: M.A
Out[819]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]], dtype=int32)

In [820]: sparse.triu(M).A
Out[820]: 
array([[0, 1, 2],
       [0, 4, 5],
       [0, 0, 8]], dtype=int32)

您可能需要構造一個新的稀疏矩陣,其中非零值僅高於閾值。

In [826]: sparse.triu(M>2).A
Out[826]: 
array([[False, False, False],
       [False,  True,  True],
       [False, False,  True]], dtype=bool)

In [827]: sparse.triu(M>2).nonzero()
Out[827]: (array([1, 1, 2], dtype=int32), array([1, 2, 2], dtype=int32))

這是triu的代碼:

def triu(A, k=0, format=None):
    A = coo_matrix(A, copy=False)
    mask = A.row + k <= A.col
    row = A.row[mask]
    col = A.col[mask]
    data = A.data[mask]
    return coo_matrix((data,(row,col)), shape=A.shape).asformat(format)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM