bz13531
bz13531

Reputation: 59

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

So I have a COO matrix "coo_mat" created using scipy.sparse, with the first three non-zero elements being:

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

I wish to multiply the matrix by 2, and I understand that I can simply do:

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

However, I don't understand why the results are not consistent when I try:

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

I've used the element-wise multiplication method in other analyses and it was working as I expected. Is there something I missing when using sparse.coo_matrix.multiply().

Upvotes: 1

Views: 833

Answers (1)

user2357112
user2357112

Reputation: 282026

SciPy doesn't promise anything about the output format of most sparse matrix operations. It can reorder the elements of a COO matrix, or even switch formats to CSR or CSC or something. Here, coo_mat.multiply(2) is returning a CSR matrix with a completely different element representation and element layout:

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 its multiply method from the scipy.sparse.spmatrix base class, which implements multiply as

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

There's no optimization for COO in that method.

Upvotes: 2

Related Questions