用非零元素的数量归一化 scipy 稀疏矩阵

Normalize scipy sparse matrix with number of nonzero elements

我想将 csr_matrix 的每一行除以该行中非零条目的数量。

例如:考虑一个 csr_matrix A:

A = [[6, 0, 0, 4, 0], [3, 18, 0, 9, 0]]
Result = [[3, 0, 0, 2, 0], [1, 6, 0, 3, 0]]

最短且最有效的方法是什么?

Divakar 给出了一个in-place方法。我的试用创建了一个新数组。

from scipy import sparse
A = sparse.csr_matrix([[6, 0, 0, 4, 0], [3, 18, 0, 9, 0]])
A.multiply(1.0/(A != 0).sum(axis=1)) 

我们将每行中 non-zero 个部分之和的倒数相乘。请注意,可能需要确保没有 dividing-by-zero 错误。

正如 Divakar 所指出的:A.multiply(1.0/...) 需要 1.0 而不是 1 才能与 Python 兼容 2.

使用getnnz方法获取计数,然后将in-place复制并划分为使用data方法获得的扁平化视图-

s = A.getnnz(axis=1)
A.data /= np.repeat(s, s)

灵感来自 .

样本运行-

In [15]: from scipy.sparse import csr_matrix

In [16]: A = csr_matrix([[6, 0, 0, 4, 0], [3, 18, 0, 9, 0]])

In [18]: s = A.getnnz(axis=1)
    ...: A.data /= np.repeat(s, s)

In [19]: A.toarray()
Out[19]: 
array([[3, 0, 0, 2, 0],
       [1, 6, 0, 3, 0]])

注意:为了在 Python2 和 3 之间兼容,我们可能需要使用 // -

A.data //=  ...