multiply 方法进行元素乘法。
这是一个示例,其中a 和b 是具有COO 格式的稀疏矩阵。 (.A 属性返回一个常规的 numpy 数组。我用它来显示稀疏矩阵中的值。)
In [41]: a
Out[41]:
<5x8 sparse matrix of type '<class 'numpy.int64'>'
with 20 stored elements in COOrdinate format>
In [42]: a.A
Out[42]:
array([[0, 9, 2, 9, 0, 6, 6, 2],
[2, 0, 0, 0, 1, 0, 8, 0],
[0, 3, 0, 0, 2, 9, 0, 4],
[0, 0, 0, 0, 0, 0, 0, 5],
[0, 0, 7, 1, 0, 0, 7, 7]])
In [43]: b
Out[43]:
<5x8 sparse matrix of type '<class 'numpy.int64'>'
with 20 stored elements in COOrdinate format>
In [44]: b.A
Out[44]:
array([[0, 0, 0, 7, 9, 0, 5, 0],
[0, 7, 0, 0, 6, 6, 0, 0],
[3, 0, 2, 0, 3, 0, 0, 0],
[5, 0, 0, 3, 0, 0, 7, 0],
[8, 0, 6, 8, 0, 0, 4, 0]])
计算a 和b 的元素乘积。请注意,c 使用 CSR 格式。
In [45]: c = a.multiply(b)
In [46]: c
Out[46]:
<5x8 sparse matrix of type '<class 'numpy.int64'>'
with 7 stored elements in Compressed Sparse Row format>
In [47]: c.A
Out[47]:
array([[ 0, 0, 0, 63, 0, 0, 30, 0],
[ 0, 0, 0, 0, 6, 0, 0, 0],
[ 0, 0, 0, 0, 6, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 42, 8, 0, 0, 28, 0]], dtype=int64)
通过计算相应 numpy 数组的元素乘积来验证结果。
In [48]: a.A * b.A
Out[48]:
array([[ 0, 0, 0, 63, 0, 0, 30, 0],
[ 0, 0, 0, 0, 6, 0, 0, 0],
[ 0, 0, 0, 0, 6, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 42, 8, 0, 0, 28, 0]])