您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

不幸的是,.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]
其他 2022/1/1 18:49:28 有447人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶