python稀疏矩阵获取最大值和索引

KEX*_*ANG 5 python csr scipy sparse-matrix

我有一个稀疏矩阵A(密集等于10*3),例如:

print type(A)
<class scipy.sparse.csr.csr_matrix>

print A
(0, 0)  0.0160478743808
(0, 2)  0.0317314165078
(1, 2)  0.0156596521648
(1, 0)  0.0575683686558
(2, 2)  0.0107481166871
(3, 0)  0.0150580924929
(3, 2)  0.0297743235876
(4, 0)  0.0161931803955
(4, 2)  0.0320187296788
(5, 2)  0.0106034409766
(5, 0)  0.0128109177074
(6, 2)  0.0105766993238
(6, 0)  0.0127786088452
(7, 2)  0.00926522256063
(7, 0)  0.0111941023699
Run Code Online (Sandbox Code Playgroud)

每列的最大值为:

print A.max(axis=0)
(0, 0)  0.0575683686558
(0, 2)  0.0320187296788
Run Code Online (Sandbox Code Playgroud)

我想得到与列值对应索引.我知道的

A.getcol(i).tolist()
Run Code Online (Sandbox Code Playgroud)将返回每个列的列表,允许我使用argmax()函数,但这种方式真的很慢.我想知道有什么下降的方法吗?

War*_*ser 1

这是您在问题中建议的方法的细微变化:

col_argmax = [A.getcol(i).A.argmax() for i in range(A.shape[1])]
Run Code Online (Sandbox Code Playgroud)

(该.A属性相当于.toarray()。)

一个可能更有效的替代方案是

B = A.tocsc()
col_argmax = [B.indices[B.indptr[i] + B.data[B.indptr[i]:B.indptr[i+1]].argmax()] for i in range(len(B.indptr)-1)]
Run Code Online (Sandbox Code Playgroud)

以上任一方法都可以,但我必须问:如果你的数组的形状为 (10, 3),为什么要使用稀疏矩阵?(10, 3) 很小!只需使用常规的密集 numpy 数组即可。

即使保留A为稀疏矩阵,计算该大小的矩阵列的 argmax 的最有效方法可能是将其转换为密集数组并使用 argmax 方法:

col_argmax = A.A.argmax(axis=0)
Run Code Online (Sandbox Code Playgroud)