python中稀疏矩阵的逐元素乘法

use*_*329 4 numpy scipy python-2.7

我想知道是否有一个运算符用于将稀疏矩阵的行与 scipy.sparse 库中的向量进行按元素相乘。类似于 numpy 数组的 A*b 吗?谢谢。

War*_*ser 5

使用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]])
Run Code Online (Sandbox Code Playgroud)

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]])
Run Code Online (Sandbox Code Playgroud)