初始化高维稀疏矩阵

2022-04-13 00:00:00 python numpy scipy sparse-matrix

问题描述

我希望使用sklearn初始化300,000 x 300,0000稀疏矩阵,但它需要内存,就像它不是稀疏矩阵一样:

>>> from scipy import sparse
>>> sparse.rand(300000,300000,.1)   

它显示错误:

MemoryError: Unable to allocate 671. GiB for an array with shape (300000, 300000) and data type float64

这与我使用numpy进行初始化时的错误相同:

np.random.normal(size=[300000, 300000])

即使我的密度非常低,它也会重现错误:

>>> from scipy import sparse
>>> from scipy import sparse
>>> sparse.rand(300000,300000,.000000000001)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../python3.8/site-packages/scipy/sparse/construct.py", line 842, in rand
    return random(m, n, density, format, dtype, random_state)
  File ".../lib/python3.8/site-packages/scipy/sparse/construct.py", line 788, in random
    ind = random_state.choice(mn, size=k, replace=False)
  File "mtrand.pyx", line 980, in numpy.random.mtrand.RandomState.choice
  File "mtrand.pyx", line 4528, in numpy.random.mtrand.RandomState.permutation
MemoryError: Unable to allocate 671. GiB for an array with shape (90000000000,) and data type int64

有没有更省内存的方法来创建这样的稀疏矩阵?


解决方案

只生成您需要的内容。

from scipy import sparse
import numpy as np

n, m = 300000, 300000
density = 0.00000001
size = int(n * m * density)

rows = np.random.randint(0, n, size=size)
cols = np.random.randint(0, m, size=size)
data = np.random.rand(size)

arr = sparse.csr_matrix((data, (rows, cols)), shape=(n, m))

这使您可以构建怪物稀疏数组,前提是它们足够稀疏,可以放入内存中。

>>> arr
<300000x300000 sparse matrix of type '<class 'numpy.float64'>'
    with 900 stored elements in Compressed Sparse Row format>

这可能就是parse.rand构造函数无论如何都应该工作的方式。如果任何行、列对发生冲突,它会将数据值相加在一起,这可能适用于我能想到的所有应用程序。

相关文章