将稀疏数组中的元素与矩阵中的行相乘


问题内容

如果矩阵X稀疏:

>> X = csr_matrix([[0,2,0,2],[0,2,0,1]])
>> print type(X)    
>> print X.todense()    
<class 'scipy.sparse.csr.csr_matrix'>
[[0 2 0 2]
 [0 2 0 1]]

和矩阵Y:

>> print type(Y)
>> print text_scores
<class 'numpy.matrixlib.defmatrix.matrix'>
[[8]
 [5]]

…如何将X的每个元素乘以Y的行。例如:

[[0*8 2*8 0*8 2*8]
 [0*5 2*5 0*5 1*5]]

要么:

[[0 16 0 16]
 [0 10 0 5]]

我对此感到厌倦,但是显然由于尺寸不匹配而无法正常工作: Z = X.data * Y


问题答案:

不幸的是,.multiply如果另一个CSR矩阵密集,则CSR矩阵的方法似乎会使该矩阵致密。因此,这是避免这种情况的一种方法:

# Assuming that Y is 1D, might need to do Y = Y.A.ravel() or such...

# just to make the point that this works only with CSR:
if not isinstance(X, scipy.sparse.csr_matrix):
    raise ValueError('Matrix must be CSR.')

Z = X.copy()
# simply repeat each value in Y by the number of nnz elements in each row: 
Z.data *= Y.repeat(np.diff(Z.indptr))

这确实会创建一些临时对象,但至少将其完全矢量化,并且不会使稀疏矩阵致密。


对于COO矩阵,等效项是:

Z.data *= Y[Z.row] # you can use np.take which is faster then indexing.

对于CSC矩阵,等效项为:

Z.data *= Y[Z.indices]