不幸的是,.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]