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

标签 python-2.7 numpy scipy

我想知道 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/

相关文章:

python - 将字符串列表转换为元组

python - PIP - 如何从本地文件夹安装依赖项?

python - 两个稀疏矩阵的逐元素最大值

python - 获取 numpy.poly1d 曲线的最小点

python - 尝试绘制简单柱形图时遇到 "TypeError: integer argument expected, got float"

python - 让 Scapy 在 Windows 上工作时出错 : "' module' object has no attribute 'ex_name' "

python - python scipy 中样条线与平面的相交

指定范围内的Python bin数据

python - 如何根据层次结构计算列值

python - scipy.optimize linprog 不会返回我期望的最小解决方案