I want to initialize 300,000 x 300,0000
sparse matrix using sklearn
, but it requires memory as if it was not sparse:
JavaScript
x
3
1
>>> from scipy import sparse
2
>>> sparse.rand(300000,300000,.1)
3
it gives the error:
JavaScript
1
2
1
MemoryError: Unable to allocate 671. GiB for an array with shape (300000, 300000) and data type float64
2
which is the same error as if I initialize using numpy
:
JavaScript
1
2
1
np.random.normal(size=[300000, 300000])
2
Even when I go to a very low density, it reproduces the error:
JavaScript
1
13
13
1
>>> from scipy import sparse
2
>>> from scipy import sparse
3
>>> sparse.rand(300000,300000,.000000000001)
4
Traceback (most recent call last):
5
File "<stdin>", line 1, in <module>
6
File ".../python3.8/site-packages/scipy/sparse/construct.py", line 842, in rand
7
return random(m, n, density, format, dtype, random_state)
8
File ".../lib/python3.8/site-packages/scipy/sparse/construct.py", line 788, in random
9
ind = random_state.choice(mn, size=k, replace=False)
10
File "mtrand.pyx", line 980, in numpy.random.mtrand.RandomState.choice
11
File "mtrand.pyx", line 4528, in numpy.random.mtrand.RandomState.permutation
12
MemoryError: Unable to allocate 671. GiB for an array with shape (90000000000,) and data type int64
13
Is there a more memory-efficient way to create such a sparse matrix?
Advertisement
Answer
Just generate only what you need.
JavaScript
1
13
13
1
from scipy import sparse
2
import numpy as np
3
4
n, m = 300000, 300000
5
density = 0.00000001
6
size = int(n * m * density)
7
8
rows = np.random.randint(0, n, size=size)
9
cols = np.random.randint(0, m, size=size)
10
data = np.random.rand(size)
11
12
arr = sparse.csr_matrix((data, (rows, cols)), shape=(n, m))
13
This lets you build monster sparse arrays provided they’re sparse enough to fit into memory.
JavaScript
1
4
1
>>> arr
2
<300000x300000 sparse matrix of type '<class 'numpy.float64'>'
3
with 900 stored elements in Compressed Sparse Row format>
4
This is probably how the sparse.rand constructor should be working anyway. If any row, col pairs collide it’ll add the data values together, which is probably fine for all applications I can think of.