我想知道 scipy.sparse 库中是否有用于将稀疏矩阵的行与向量逐元素相乘的运算符。类似于 numpy 数组的 A*b 的东西?谢谢。
最佳答案
使用 multiply
方法:
In [15]: a
Out[15]:
<3x5 sparse matrix of type '<type 'numpy.int64'>'
with 5 stored elements in Compressed Sparse Row format>
In [16]: a.A
Out[16]:
array([[1, 0, 0, 2, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 4, 5]])
In [17]: x
Out[17]: array([ 5, 10, 15, 20, 25])
In [18]: a.multiply(x)
Out[18]:
matrix([[ 5, 0, 0, 40, 0],
[ 0, 0, 45, 0, 0],
[ 0, 0, 0, 80, 125]])
请注意,如果 x
是常规 numpy 数组 (ndarray
),则结果不是稀疏矩阵。先将x
转化为稀疏矩阵,得到稀疏结果:
In [32]: xs = csr_matrix(x)
In [33]: y = a.multiply(xs)
In [34]: y
Out[34]:
<3x5 sparse matrix of type '<type 'numpy.int64'>'
with 5 stored elements in Compressed Sparse Row format>
In [35]: y.A
Out[35]:
array([[ 5, 0, 0, 40, 0],
[ 0, 0, 45, 0, 0],
[ 0, 0, 0, 80, 125]])
关于python-2.7 - python中稀疏矩阵的逐元素乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25494305/