小编cat*_*mic的帖子

具有广播的稀疏 Scipy 矩阵和向量的元素最大值

我需要一个快速的逐元素最大值,它将 n×m scipy 稀疏矩阵元素的每一行与稀疏的 1×m 矩阵进行比较。这在 Numpy 中使用np.maximum(mat, vec)通过 Numpy 的广播完美地工作。

但是,Scipy's.maximum()没有广播。我的矩阵很大,所以我不能将它转换为一个 numpy 数组。

我目前的解决方法是使用mat[row,:].maximum(vec). 这个大循环正在破坏我的代码效率(必须多次执行)。我的缓慢解决方案在下面的第二个代码片段中 - 有更好的解决方案吗?

# Example
import numpy as np
from scipy import sparse

mat = sparse.csc_matrix(np.arange(12).reshape((4,3)))

vec = sparse.csc_matrix([-1, 5, 100])

# Numpy's np.maximum() gives the **desired result** using broadcasting (but it can't handle sparse matrices):
numpy_result = np.maximum( mat.toarray(), vec.toarray() )
print( numpy_result )
# [[  0   5 100]
#  [  3   5 100]
#  [ …
Run Code Online (Sandbox Code Playgroud)

python numpy scipy sparse-matrix elementwise-operations

6
推荐指数
1
解决办法
311
查看次数