繁体   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