Given the code snippet:
JavaScript
x
2
1
B = A @ M - T
2
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.
JavaScript
1
9
1
>>> import numpy as np
2
>>> from scipy import sparse
3
>>> A = sparse.random(100, 10, density=0.1, format='csr')
4
>>> B = np.random.rand(10, 10)
5
>>> type(A@B)
6
<class 'numpy.ndarray'>
7
>>> type(B@A.T)
8
<class 'numpy.ndarray'>
9
Note that some sparse operations still give matrixes, not arrays:
JavaScript
1
4
1
>>> N = sparse.random(100, 10, density=0.1, format='csr')
2
>>> type(A@B - N)
3
<class 'numpy.matrix'>
4