【问题标题】:Initialize high dimensional sparse matrix初始化高维稀疏矩阵
【发布时间】:2020-11-16 13:39:47
【问题描述】:

我想用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

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

【问题讨论】:

  • 在哪里指定矩阵总体的密度?据我所知,您在非备用矩阵上使用备用数据结构。
  • @kpie density=0.1? sparse.rand 中的第三个参数。即使你我选择更少(例如,密度 = 0),它仍然会给出相同的错误
  • sparse.rand 使用 choice 从 300000*300000 整数空间生成 k 随机索引。我经常使用这个函数来生成样本稀疏矩阵,但通常只是为了一个合理的测试用例,比如 10x10。显然,这并不是一种生成非常大矩阵的方式,无论您制作的矩阵有多稀疏。最终的矩阵不会占用这么多空间,但这种生成索引的方法确实暂时需要它。
  • scipy.sparse 有多种创建稀疏矩阵的方法。一个常见的使用 3 coo 样式数组 - 您可以选择您选择的索引和数据值。较慢的方法是从正确形状的lil 开始,然后“随机”分配元素。 sparse.random 只是用于创建测试矩阵的便捷工具,很少用于生产目的。

标签: python numpy scipy sparse-matrix


【解决方案1】:

只生成你需要的东西。

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>

这可能是 sparse.rand 构造函数无论如何应该如何工作的。如果任何行、col 对发生碰撞,它会将数据值加在一起,这对于我能想到的所有应用程序来说可能都很好。

【讨论】:

    【解决方案2】:

    尝试传递一个合理的 density 参数,如文档中所示...如果您有 10 万亿个细胞,可能像 0.00000001 或其他东西...

    https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.rand.html#scipy.sparse.rand

    【讨论】:

      【解决方案3】:

      @hpaulj 的评论很到位。错误信息中也有线索。

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

      有一个对 int64 而不是 float64 的引用和一个大小为 300,000 X 300,000 的线性数组。这指的是在创建稀疏矩阵的过程中进行随机抽样的中间步骤,无论如何这会占用大量内存。

      请注意,在创建任何稀疏矩阵(无论格式如何)时,您必须为非零值和表示值在矩阵中的位置考虑内存。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-19
        • 2021-12-07
        相关资源
        最近更新 更多