python中稀疏矩阵的元素乘法

时间:2014-08-25 20:59:54

标签: python-2.7 numpy scipy

我想知道是否存在一个运算符,用于在scipy.sparse库中使用向量的稀疏矩阵的行元素乘法。 numpy数组类似于A * b的东西?感谢。

1 个答案:

答案 0 :(得分:2)

使用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]])
相关问题