[英]Python Scipy How to traverse upper/lower trianglar portion non-zeros from csr_matrix
I have a very sparse matrix(similarity matrix) with dimensions 300k * 300k. 我有一个非常稀疏的矩阵(相似性矩阵),尺寸为300k * 300k。 In order to find out the relatively greater similarities between users, I only need upper/lower triangular portion of the matrix.
为了找出用户之间相对较大的相似性,我只需要矩阵的上/下三角部分。 So, how to get the coordinates of users with value larger than a threshold in an efficient way?
那么,如何有效地获取值大于阈值的用户坐标呢? Thanks.
谢谢。
How about 怎么样
sparse.triu(M)
If M
is 如果
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)
You may need to construct a new sparse matrix, with just nonzeros above the threshold. 您可能需要构造一个新的稀疏矩阵,其中非零值仅高于阈值。
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))
Here's the code for triu
: 这是
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.