我想使用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
有没有一种更节省内存的方式来创建这样的稀疏矩阵?
density=0.1
是sparse.rand
中的第三个参数。即使我选择更小的值(例如,density=0),它仍然会给出相同的错误。 - randosparse.rand
函数使用choice
方法从一个大小为300000*300000的整数空间中生成k个随机索引。我经常使用该函数生成稀疏矩阵的样本,但通常只针对10x10这样的合理测试用例。显然,这并不是一种无论你如何稀疏化都可以生成非常大矩阵的方法。最终的矩阵不会占用这么多空间,但是生成索引的方法需要暂时占用这么多空间。 - hpauljscipy.sparse
提供了多种创建稀疏矩阵的方法。其中一种常用方法是使用 3 个coo
格式的数组,您可以选择索引和数据值。另一种较慢的方法是从正确形状的lil
开始,并“随机”分配元素。sparse.random
只是一个方便的工具,用于创建测试矩阵,很少用于实际生产目的。 - hpaulj