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.

## Advertisement

## Answer

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(B@A.T) <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'>