Skip to main content
 首页 » 编程设计

python之numpy 和稀疏矩阵之间的点积

2025年01月19日14jpfss

假设我们有以下数据:

import numpy as np 
from scipy.sparse import csr_matrix  
A = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) # (3,3) 
B = np.array([[1,2],[2,3],[3,3]]) # (2,3) 

然后:

A.dot(B) 
array([[ 5,  8], 
       [ 9,  9], 
       [19, 23]]) 

在上面我们有 sparce_matrix.dot(numpy_matrix) 并且输出是 (3,2)`。但如果我改变:

B = np.array([[1,2,3],[2,3,3],[3,3,3]]) 

和:

B.dot(A) 
array([[ <3x3 sparse matrix of type '<type 'numpy.int64'>' 
     with 5 stored elements in Compressed Sparse Row format>, 
    <3x3 sparse matrix of type '<type 'numpy.int64'>' 
    with 5 stored elements in Compressed Sparse Row format>, 
    <3x3 sparse matrix of type '<type 'numpy.int64'>' 
    with 5 stored elements in Compressed Sparse Row format>], 
   [ <3x3 sparse matrix of type '<type 'numpy.int64'>' 
    with 5 stored elements in Compressed Sparse Row format>, 
    <3x3 sparse matrix of type '<type 'numpy.int64'>' 
    with 5 stored elements in Compressed Sparse Row format>, 
    <3x3 sparse matrix of type '<type 'numpy.int64'>' 
    with 5 stored elements in Compressed Sparse Row format>], 
   [ <3x3 sparse matrix of type '<type 'numpy.int64'>' 
    with 5 stored elements in Compressed Sparse Row format>, 
    <3x3 sparse matrix of type '<type 'numpy.int64'>' 
    with 5 stored elements in Compressed Sparse Row format>, 
    <3x3 sparse matrix of type '<type 'numpy.int64'>' 
    with 5 stored elements in Compressed Sparse Row format>]], dtype=object) 

所以在上面我们有一个 numpy_matrix.dot(sparce_matrix) 并且预期的输出是 (3,3) 但它不是。

可以通过以下方式计算:

A.T.dot(B.T).T 

但为什么在第二种情况下 B.dot(A) 的输出会出现这种行为?有没有办法在不转置的情况下做到这一点?

请您参考如下方法:

B.dot(A) 被评估为 B.dot(np.array(A))。它不知道 A 是稀疏的,因为它有自己的 dot。 A.dot(B) 使用 A 的稀疏方法。

np.array(A) 不同于 A.toarray()。试试吧。

还可以尝试使用 np.dot(B, A)。它可能会给 A 控制权,但我不确定。在任何情况下都不要假设 numpy 函数可以正确处理稀疏矩阵。如果他们委托(delegate)给稀疏方法就可以了。但是测试。


In [744]: np.array(A) 
Out[744]:  
array(<3x3 sparse matrix of type '<class 'numpy.int32'>' 
    with 5 stored elements in Compressed Sparse Row format>, dtype=object) 
In [745]: _.shape 
Out[745]: () 

所以 B.dot(A) 是用“标量”对象点缀的 B。 dot 允许这样做,我几乎感到惊讶;我想知道这是否是最近发生的变化。


对于这个小例子,转置解法和toarray一次差不多。

In [750]: timeit B.dot(A.A) 
119 µs ± 319 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) 
In [751]: timeit A.T.dot(B.T).T 
102 µs ± 2.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) 

强制进行稀疏计算的另一种方法 - 使 B 稀疏

In [758]: Bs = sparse.csr_matrix(B) 
In [759]: timeit (Bs*A) 
211 µs ± 9.23 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) 

请注意,稀疏 * 密集会产生密集的结果。如果稀疏矩阵足够稀疏,它仍然比纯密集操作更快。

相对时间会随着稀疏矩阵的稀疏度以及输入和输出的大小而变化。

如果 A 太大而无法变成密集数组(时间或内存限制),B 或结果也不会太大?如果 A 有很多行和很少的列,那么 B(在 B.dot(A) 中)将必须有很多列。但是,如果 A 有很多列,结果将有同样多的列。因此,另一种方式是您将拥有一个大的密集数组,其大小与 A.toarray() 相当。