gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:52:20 30 4
gpt4 key购买 nike

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

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com