0
votes

Given the code snippet:

B = A @ M - T

where A is a CSR scipy sparse matrix, M and T are two numpy arrays.

Question: During the matrix operations, does numpy treat A as a dense matrix, or M and T as two sparse matrices?

I suspect that the latter case is true since the resulting matrix B is not in the sparse format.

I also notices that this operation is much slower if I change the format of A to dense, which sort of contradicts my guess.

1
Here Athe sparse matrix controls the operation. It does one thing if the other object is sparse, another if dense (with different result type)hpaulj
The @ like * passes the task to sparse.__mul__, which in turn calls one of several methods depending on what the other is. Follow the [source] link on this page if you want more details: docs.scipy.org/doc/scipy/reference/generated/…hpaulj

1 Answers

2
votes

Numpy doesn't do sparse matrices. Scipy does the matrix multiplication (this means no multithreading, unlike numpy).

A is kept sparse but A @ M fills a dense array if M is a dense array.

>>> import numpy as np
>>> from scipy import sparse
>>> A = sparse.random(100, 10, density=0.1, format='csr')
>>> B = np.random.rand(10, 10)
>>> type(A@B)
<class 'numpy.ndarray'>
>>> type([email protected])
<class 'numpy.ndarray'>

Note that some sparse operations still give matrixes, not arrays:

>>> N = sparse.random(100, 10, density=0.1, format='csr')
>>> type(A@B - N)
<class 'numpy.matrix'>