SciPy 稀疏矩阵“.multiply”未返回预期结果?

SciPy sparse matrix ".multiply" not returning expected results?

所以我有一个使用 scipy.sparse 创建的 COO 矩阵 "coo_mat",前三个非零元素是:

coo_mat.data[:5]
>>> array([0.61992174, 1.30911574, 1.48995508])

我想将矩阵乘以 2,我知道我可以简单地这样做:

(coo_mat*2).data[:5]
>>> array([1.23984347, 2.61823147, 2.97991015])

但是,我不明白为什么我尝试时结果不一致:

coo_mat.multiply(2).data[:5]
>>> array([2.04156392, 1.54042948, 2.3306947 ])

我在其他分析中使用了按元素相乘的方法,它按我的预期工作。使用 sparse.coo_matrix.multiply().

时我遗漏了什么吗?

SciPy 不保证大多数稀疏矩阵运算的输出格式。它可以对 COO 矩阵的元素进行重新排序,甚至可以将格式切换为 CSR 或 CSC 等。在这里,coo_mat.multiply(2) 返回一个具有完全不同的元素表示和元素布局的 CSR 矩阵:

In [11]: x = scipy.sparse.coo_matrix([[1]])

In [12]: type(x.multiply(2))
Out[12]: scipy.sparse.csr.csr_matrix

scipy.sparse.coo_matrix inherits 它的 multiply 方法来自 scipy.sparse.spmatrix 基础 class,它将 multiply 实现为

def multiply(self, other):
    """Point-wise multiplication by another matrix
    """
    return self.tocsr().multiply(other)

该方法中没有针对 COO 的优化。